// Module: Mantenimiento

function MantenimientoModule() {
  const { state, dispatch } = useStore();
  const toast = useToast();
  const [tab, setTab] = useState('plan');
  const [adding, setAdding] = useState(false);
  const [resolving, setResolving] = useState(null);

  const overdue = state.maintenance.filter((m) => m.status === 'overdue').length;
  const soon = state.maintenance.filter((m) => m.status === 'soon').length;

  return (
    <div className="view-in space-y-5">
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <Card>
          <CardContent className="pt-5">
            <div className="text-[11px] font-semibold text-muted uppercase tracking-wider">
              Tareas en plan
            </div>
            <div className="text-[26px] font-bold tracking-tight tnum mt-2">
              {state.maintenance.length}
            </div>
            <div className="text-[11px] text-muted mt-1">Rig-1 activo</div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-5">
            <div className="text-[11px] font-semibold text-muted uppercase tracking-wider">
              Vencidas
            </div>
            <div
              className={cn(
                'text-[26px] font-bold tracking-tight tnum mt-2',
                overdue > 0 && 'text-red',
              )}
            >
              {overdue}
            </div>
            <div className="text-[11px] text-muted mt-1">requiere acción</div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-5">
            <div className="text-[11px] font-semibold text-muted uppercase tracking-wider">
              Próximas 48 hs
            </div>
            <div
              className={cn(
                'text-[26px] font-bold tracking-tight tnum mt-2',
                soon > 0 && 'text-amber-ink',
              )}
            >
              {soon}
            </div>
            <div className="text-[11px] text-muted mt-1">planificar</div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-5">
            <div className="text-[11px] font-semibold text-muted uppercase tracking-wider">
              Services en 2026
            </div>
            <div className="text-[26px] font-bold tracking-tight tnum mt-2">
              {state.maintHistory.length}
            </div>
            <div className="text-[11px] text-muted mt-1">historial</div>
          </CardContent>
        </Card>
      </div>

      <Card>
        <div className="px-5 py-3 border-b border-border flex items-center justify-between flex-wrap gap-3">
          <Tabs
            value={tab}
            onChange={setTab}
            options={[
              { value: 'plan', label: 'Plan preventivo' },
              { value: 'history', label: 'Historial' },
            ]}
          />
          <div className="flex items-center gap-2">
            <Button variant="outline" size="sm">
              <Icon name="calendar" size={12} /> Ver calendario
            </Button>
            <Button variant="primary" size="sm" onClick={() => setAdding(true)}>
              <Icon name="plus" size={12} /> Registrar service
            </Button>
          </div>
        </div>

        {tab === 'plan' && (
          <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">Estado</th>
                  <th className="text-left px-3 py-2.5">Equipo</th>
                  <th className="text-left px-3 py-2.5">Tarea</th>
                  <th className="text-right px-3 py-2.5">Intervalo</th>
                  <th className="text-right px-3 py-2.5">Últ. hs</th>
                  <th className="text-right px-3 py-2.5">Actuales</th>
                  <th className="px-3 py-2.5 w-40">Progreso</th>
                  <th className="text-right px-5 py-2.5">Acción</th>
                </tr>
              </thead>
              <tbody>
                {state.maintenance.map((m) => {
                  const used = m.currentHs - m.lastHs;
                  const pct = (used / m.intervalHs) * 100;
                  return (
                    <tr key={m.id} className="border-t border-border hover:bg-slate-50/60">
                      <td className="px-5 py-3">
                        {m.status === 'overdue' && <Badge variant="red">Vencida</Badge>}
                        {m.status === 'soon' && <Badge variant="amber">48 hs</Badge>}
                        {m.status === 'ok' && <Badge variant="emerald">OK</Badge>}
                      </td>
                      <td className="px-3 py-3 font-medium">{m.equipment}</td>
                      <td className="px-3 py-3">{m.task}</td>
                      <td className="px-3 py-3 text-right tnum text-muted">{m.intervalHs} hs</td>
                      <td className="px-3 py-3 text-right tnum text-muted">{m.lastHs} hs</td>
                      <td className="px-3 py-3 text-right tnum font-semibold">{m.currentHs} hs</td>
                      <td className="px-3 py-3">
                        <div className="flex items-center gap-2">
                          <div className="flex-1 h-1.5 rounded-full bg-slate-100 overflow-hidden">
                            <div
                              className={cn(
                                'h-full rounded-full',
                                m.status === 'overdue'
                                  ? 'bg-red'
                                  : m.status === 'soon'
                                    ? 'bg-amber'
                                    : 'bg-emerald',
                              )}
                              style={{ width: `${Math.min(100, pct)}%` }}
                            />
                          </div>
                          <span className="text-[10.5px] tnum text-muted min-w-10 text-right">
                            {Math.round(pct)}%
                          </span>
                        </div>
                      </td>
                      <td className="px-5 py-3 text-right">
                        <Button variant="outline" size="sm" onClick={() => setResolving(m)}>
                          <Icon name="check" size={12} /> Resolver
                        </Button>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}

        {tab === 'history' && (
          <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">Equipo</th>
                  <th className="text-left px-3 py-2.5">Tipo</th>
                  <th className="text-left px-3 py-2.5">Técnico</th>
                  <th className="text-right px-3 py-2.5">Horas motor</th>
                  <th className="text-left px-5 py-2.5">Observaciones</th>
                </tr>
              </thead>
              <tbody>
                {state.maintHistory.map((h) => (
                  <tr key={h.id} className="border-t border-border hover:bg-slate-50/60">
                    <td className="px-5 py-3 tnum text-muted">{h.date}</td>
                    <td className="px-3 py-3 font-medium">{h.equipment}</td>
                    <td className="px-3 py-3">
                      <Badge variant="outline">{h.type}</Badge>
                    </td>
                    <td className="px-3 py-3">{h.tech}</td>
                    <td className="px-3 py-3 text-right tnum">{h.hours} hs</td>
                    <td className="px-5 py-3 text-muted">{h.notes}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Card>

      <ServiceDialog
        open={adding}
        onClose={() => setAdding(false)}
        onSave={(item) => {
          dispatch({ type: 'maint/addHistory', item });
          toast({
            title: 'Service registrado',
            description: `${item.type} · ${item.equipment}`,
            variant: 'success',
          });
          setAdding(false);
        }}
      />

      {resolving && (
        <Dialog
          open={true}
          onClose={() => setResolving(null)}
          title={`Resolver · ${resolving.task}`}
          description={`Equipo ${resolving.equipment} · intervalo ${resolving.intervalHs} hs`}
          footer={
            <>
              <Button variant="outline" size="sm" onClick={() => setResolving(null)}>
                Cancelar
              </Button>
              <Button
                variant="primary"
                size="sm"
                onClick={() => {
                  dispatch({
                    type: 'maint/resolve',
                    id: resolving.id,
                    task: resolving.task,
                    equipment: resolving.equipment,
                    hours: resolving.currentHs,
                    tech: 'M. Álvarez',
                    notes: 'Resuelto desde plan.',
                  });
                  toast({
                    title: 'Tarea resuelta',
                    description: resolving.task,
                    variant: 'success',
                  });
                  setResolving(null);
                }}
              >
                Confirmar resolución
              </Button>
            </>
          }
        >
          <p className="text-[13px] text-muted">
            Se registrará la tarea como completada al valor actual de{' '}
            <b className="text-ink tnum">{resolving.currentHs} hs</b> y se reiniciará el contador
            del intervalo.
          </p>
        </Dialog>
      )}
    </div>
  );
}

function ServiceDialog({ open, onClose, onSave }) {
  const [f, setF] = useState({
    date: new Date().toISOString().slice(0, 10),
    equipment: 'Rig-1',
    type: 'Cambio de aceite',
    tech: '',
    hours: 0,
    notes: '',
  });
  useEffect(() => {
    if (open)
      setF({
        date: new Date().toISOString().slice(0, 10),
        equipment: 'Rig-1',
        type: 'Cambio de aceite',
        tech: '',
        hours: 0,
        notes: '',
      });
  }, [open]);
  const valid = f.tech && f.hours > 0;
  return (
    <Dialog
      open={open}
      onClose={onClose}
      title="Registrar service"
      description="Cargar un service o intervención al historial de mantenimiento."
      footer={
        <>
          <Button variant="outline" size="sm" onClick={onClose}>
            Cancelar
          </Button>
          <Button variant="primary" size="sm" disabled={!valid} onClick={() => onSave(f)}>
            Guardar service
          </Button>
        </>
      }
    >
      <div className="grid grid-cols-2 gap-4">
        <div>
          <Label>Fecha</Label>
          <Input
            type="date"
            value={f.date}
            onChange={(e) => setF({ ...f, date: e.target.value })}
          />
        </div>
        <div>
          <Label>Equipo</Label>
          <Select value={f.equipment} onChange={(e) => setF({ ...f, equipment: e.target.value })}>
            <option>Rig-1</option>
            <option>Rig-2</option>
          </Select>
        </div>
        <div className="col-span-2">
          <Label>Tipo de intervención</Label>
          <Select value={f.type} onChange={(e) => setF({ ...f, type: e.target.value })}>
            <option>Cambio de aceite</option>
            <option>Cambio filtros</option>
            <option>Service general</option>
            <option>Revisión bomba de lodo</option>
            <option>Inspección cabezales</option>
            <option>Reparación</option>
          </Select>
        </div>
        <div>
          <Label>Técnico responsable</Label>
          <Input
            value={f.tech}
            onChange={(e) => setF({ ...f, tech: e.target.value })}
            placeholder="Ej: M. Álvarez"
          />
        </div>
        <div>
          <Label>Horas motor</Label>
          <Input
            type="number"
            value={f.hours}
            onChange={(e) => setF({ ...f, hours: Number(e.target.value) })}
          />
        </div>
        <div className="col-span-2">
          <Label>Observaciones</Label>
          <Textarea
            rows={3}
            value={f.notes}
            onChange={(e) => setF({ ...f, notes: e.target.value })}
            placeholder="Detalles, repuestos usados, próximos pasos…"
          />
        </div>
      </div>
    </Dialog>
  );
}

Object.assign(window, { MantenimientoModule });
