// Module: Parte diario

function ParteModule() {
  const { state, dispatch } = useStore();
  const toast = useToast();
  const [mode, setMode] = useState('list'); // 'list' | 'new'
  const [form, setForm] = useState(emptyForm());

  function emptyForm() {
    return {
      date: new Date().toISOString().slice(0, 10),
      shift: 'Mañana',
      operator: '',
      rig: 'Rig-1',
      metersDrilled: 0,
      hoursOp: 0,
      events: 0,
      startDepth: 0,
      endDepth: 0,
      fluidType: 'Bentonita',
      fluidVolume: 0,
      weatherNotes: '',
      notes: '',
    };
  }

  const valid = form.operator.trim() && form.metersDrilled >= 0 && form.hoursOp > 0;
  const completion = Math.round(
    ([
      form.operator,
      form.metersDrilled,
      form.hoursOp,
      form.startDepth,
      form.endDepth,
      form.notes,
    ].filter((v) => v !== '' && v !== 0).length /
      6) *
      100,
  );

  function submit() {
    if (!valid) {
      toast({
        title: 'Campos requeridos',
        description: 'Operador, metros y horas son obligatorios.',
        variant: 'error',
      });
      return;
    }
    dispatch({ type: 'parte/submit', report: form });
    toast({
      title: 'Parte enviado',
      description: `${form.date} · ${form.shift} · ${form.operator}`,
      variant: 'success',
    });
    setForm(emptyForm());
    setMode('list');
  }

  if (mode === 'new') {
    return (
      <div className="view-in space-y-5">
        <div className="flex items-center justify-between">
          <div>
            <button
              onClick={() => setMode('list')}
              className="text-[12px] text-muted hover:text-ink flex items-center gap-1"
            >
              <Icon name="chevronRight" size={11} className="rotate-180" /> Volver al listado
            </button>
            <h2 className="text-[18px] font-bold tracking-tight mt-2">Nuevo parte diario</h2>
            <p className="text-[12px] text-muted mt-0.5">
              Cargá el reporte de operaciones del turno. Reemplaza el parte en papel/Excel.
            </p>
          </div>
          <div className="text-right">
            <div className="text-[11px] text-muted uppercase tracking-wider">Completitud</div>
            <div className="flex items-center gap-2 mt-1">
              <div className="w-24 h-1.5 rounded-full bg-slate-100 overflow-hidden">
                <div className="h-full bg-amber rounded-full" style={{ width: `${completion}%` }} />
              </div>
              <span className="text-[12px] font-semibold tnum">{completion}%</span>
            </div>
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
          <div className="lg:col-span-2 space-y-4">
            <Card>
              <CardHeader>
                <CardTitle>Identificación del turno</CardTitle>
                <CardDescription>Quién, cuándo, en qué equipo.</CardDescription>
              </CardHeader>
              <CardContent className="grid grid-cols-2 gap-4 pt-0">
                <div>
                  <Label>Fecha</Label>
                  <Input
                    type="date"
                    value={form.date}
                    onChange={(e) => setForm({ ...form, date: e.target.value })}
                  />
                </div>
                <div>
                  <Label>Turno</Label>
                  <Select
                    value={form.shift}
                    onChange={(e) => setForm({ ...form, shift: e.target.value })}
                  >
                    <option>Mañana</option>
                    <option>Tarde</option>
                    <option>Noche 18-24</option>
                    <option>Noche 00-06</option>
                  </Select>
                </div>
                <div>
                  <Label>Operador a cargo *</Label>
                  <Input
                    value={form.operator}
                    onChange={(e) => setForm({ ...form, operator: e.target.value })}
                    placeholder="Ej: J. Pereyra"
                  />
                </div>
                <div>
                  <Label>Equipo</Label>
                  <Select
                    value={form.rig}
                    onChange={(e) => setForm({ ...form, rig: e.target.value })}
                  >
                    <option>Rig-1</option>
                    <option>Rig-2</option>
                  </Select>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>Operación</CardTitle>
                <CardDescription>Avance, profundidad y tiempo efectivo del turno.</CardDescription>
              </CardHeader>
              <CardContent className="grid grid-cols-2 gap-4 pt-0">
                <div>
                  <Label>Profundidad inicio (m)</Label>
                  <Input
                    type="number"
                    value={form.startDepth}
                    onChange={(e) => setForm({ ...form, startDepth: Number(e.target.value) })}
                  />
                </div>
                <div>
                  <Label>Profundidad fin (m)</Label>
                  <Input
                    type="number"
                    value={form.endDepth}
                    onChange={(e) => setForm({ ...form, endDepth: Number(e.target.value) })}
                  />
                </div>
                <div>
                  <Label>Metros perforados *</Label>
                  <Input
                    type="number"
                    value={form.metersDrilled}
                    onChange={(e) => setForm({ ...form, metersDrilled: Number(e.target.value) })}
                  />
                </div>
                <div>
                  <Label>Horas de operación *</Label>
                  <Input
                    type="number"
                    step="0.1"
                    value={form.hoursOp}
                    onChange={(e) => setForm({ ...form, hoursOp: Number(e.target.value) })}
                  />
                </div>
                <div>
                  <Label>Eventos operativos</Label>
                  <Input
                    type="number"
                    value={form.events}
                    onChange={(e) => setForm({ ...form, events: Number(e.target.value) })}
                  />
                </div>
                <div>
                  <Label>ROP calculado</Label>
                  <div className="h-9 flex items-center px-3 rounded-md bg-slate-50 border border-border text-[13px] font-semibold tnum">
                    {form.hoursOp > 0 ? (form.metersDrilled / form.hoursOp).toFixed(2) : '—'} m/h
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>Fluido de perforación</CardTitle>
              </CardHeader>
              <CardContent className="grid grid-cols-2 gap-4 pt-0">
                <div>
                  <Label>Tipo</Label>
                  <Select
                    value={form.fluidType}
                    onChange={(e) => setForm({ ...form, fluidType: e.target.value })}
                  >
                    <option>Bentonita</option>
                    <option>Polímero PAC-R</option>
                    <option>Mezcla</option>
                  </Select>
                </div>
                <div>
                  <Label>Volumen usado (L)</Label>
                  <Input
                    type="number"
                    value={form.fluidVolume}
                    onChange={(e) => setForm({ ...form, fluidVolume: Number(e.target.value) })}
                  />
                </div>
                <div className="col-span-2">
                  <Label>Condiciones ambientales</Label>
                  <Input
                    value={form.weatherNotes}
                    onChange={(e) => setForm({ ...form, weatherNotes: e.target.value })}
                    placeholder="Ej: Templado, viento moderado, sin precipitaciones"
                  />
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>Observaciones</CardTitle>
                <CardDescription>Incidentes, paradas, cambios de herramienta.</CardDescription>
              </CardHeader>
              <CardContent className="pt-0">
                <Textarea
                  rows={5}
                  value={form.notes}
                  onChange={(e) => setForm({ ...form, notes: e.target.value })}
                  placeholder="Detallá lo relevante del turno…"
                />
              </CardContent>
            </Card>
          </div>

          {/* Sidebar preview */}
          <div className="space-y-4">
            <Card className="sticky top-20">
              <CardHeader>
                <CardTitle>Resumen del parte</CardTitle>
                <CardDescription>Vista previa del reporte generado.</CardDescription>
              </CardHeader>
              <CardContent className="pt-0 space-y-3 text-[13px]">
                <div className="flex justify-between">
                  <span className="text-muted">Fecha</span>
                  <span className="font-medium tnum">{form.date}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted">Turno</span>
                  <span className="font-medium">{form.shift}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted">Operador</span>
                  <span className="font-medium">{form.operator || '—'}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted">Equipo</span>
                  <span className="font-medium">{form.rig}</span>
                </div>
                <div className="border-t border-border pt-3 space-y-3">
                  <div className="flex justify-between">
                    <span className="text-muted">Metros perforados</span>
                    <span className="font-bold tnum text-amber">{form.metersDrilled} m</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted">Horas op.</span>
                    <span className="font-semibold tnum">{form.hoursOp} h</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted">ROP</span>
                    <span className="font-semibold tnum">
                      {form.hoursOp > 0 ? (form.metersDrilled / form.hoursOp).toFixed(2) : '—'} m/h
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted">Eventos</span>
                    <span className="font-semibold tnum">{form.events}</span>
                  </div>
                </div>
                <div className="pt-3 border-t border-border flex flex-col gap-2">
                  <Button variant="primary" size="md" onClick={submit} disabled={!valid}>
                    <Icon name="check" size={14} /> Enviar parte
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => {
                      setForm(emptyForm());
                    }}
                  >
                    Limpiar formulario
                  </Button>
                </div>
                {!valid && (
                  <div className="text-[11px] text-amber-ink bg-amber-soft border border-amber/30 rounded-md p-2 flex gap-2">
                    <Icon name="alert" size={13} className="shrink-0 mt-0.5" />
                    <span>Completá operador, metros y horas para habilitar el envío.</span>
                  </div>
                )}
              </CardContent>
            </Card>
          </div>
        </div>
      </div>
    );
  }

  // LIST mode
  return (
    <div className="view-in space-y-5">
      <div className="flex items-center justify-between flex-wrap gap-3">
        <div>
          <h2 className="text-[18px] font-bold tracking-tight">Partes diarios</h2>
          <p className="text-[12px] text-muted mt-0.5">
            {state.dailyReports.length} partes registrados · Genera automáticamente el reporte
            ejecutivo.
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" size="sm">
            <Icon name="download" size={12} /> Exportar
          </Button>
          <Button variant="primary" size="sm" onClick={() => setMode('new')}>
            <Icon name="plus" size={12} /> Nuevo parte
          </Button>
        </div>
      </div>

      <Card>
        <div className="overflow-x-auto">
          <table className="w-full text-[13px]">
            <thead>
              <tr className="bg-slate-50 text-[10.5px] font-semibold text-muted uppercase tracking-wider">
                <th className="text-left px-5 py-2.5">Fecha</th>
                <th className="text-left px-3 py-2.5">Turno</th>
                <th className="text-left px-3 py-2.5">Operador</th>
                <th className="text-left px-3 py-2.5">Equipo</th>
                <th className="text-right px-3 py-2.5">Metros</th>
                <th className="text-right px-3 py-2.5">Horas</th>
                <th className="text-right px-3 py-2.5">ROP</th>
                <th className="text-right px-3 py-2.5">Eventos</th>
                <th className="text-left px-5 py-2.5">Observaciones</th>
              </tr>
            </thead>
            <tbody>
              {state.dailyReports.map((r) => (
                <tr key={r.id} className="border-t border-border hover:bg-slate-50/60">
                  <td className="px-5 py-3 tnum text-muted">{r.date}</td>
                  <td className="px-3 py-3">
                    <Badge variant="outline">{r.shift}</Badge>
                  </td>
                  <td className="px-3 py-3 font-medium">{r.operator}</td>
                  <td className="px-3 py-3">{r.rig}</td>
                  <td className="px-3 py-3 text-right tnum font-semibold">{r.metersDrilled} m</td>
                  <td className="px-3 py-3 text-right tnum">{r.hoursOp} h</td>
                  <td className="px-3 py-3 text-right tnum">
                    {r.hoursOp > 0 ? (r.metersDrilled / r.hoursOp).toFixed(2) : '—'}
                  </td>
                  <td className="px-3 py-3 text-right tnum">{r.events}</td>
                  <td className="px-5 py-3 text-muted max-w-sm truncate">{r.notes}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>

      <div className="text-[11px] text-muted text-center">
        Total acumulado del período:{' '}
        <b className="text-ink tnum">
          {state.dailyReports.reduce((s, r) => s + Number(r.metersDrilled || 0), 0)} m
        </b>
      </div>
    </div>
  );
}

Object.assign(window, { ParteModule });
