import { Icon } from "@iconify/react";
import { IconButton, Tooltip } from "@mui/material";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import {
  actualizarReloj,
  crearReloj,
  eliminarReloj,
  getRelojes,
  sincronizarReloj,
} from "../../../api/rrhh-presentismo.service";
import { useConfirmDialog } from "../../../hooks/useConfirmDialog";
import {
  Field,
  FieldsGrid,
  Footer,
  FooterActionButton,
  FormPanel,
  ListBody,
  ListPanel,
  RowActions,
  SectionTitle,
  TableWrap,
} from "../../ui/FormShell";
import { actionIconSx } from "../_shared/actionIconSx";
import { RRHHEmptyState } from "../_shared/RRHHEmptyState";

const emptyForm = () => ({
  nombre: "",
  tipo_conexion: "PLANILLA",
  protocolo_api: "GENERICO",
  url_base: "",
  api_key: "",
  tipo_auth: "NONE",
  formato_respuesta: "JSON",
  campo_documento: "documento",
  campo_timestamp: "timestamp",
  intervalo_polling_min: "",
  activo: true,
});

export function RelojesPresentismoTab() {
  const { confirm, dialogs } = useConfirmDialog();
  const [items, setItems] = useState([]);
  const [form, setForm] = useState(emptyForm());
  const [editingId, setEditingId] = useState(null);
  const [saving, setSaving] = useState(false);
  const [loading, setLoading] = useState(false);

  const load = async () => {
    setLoading(true);
    try {
      const res = await getRelojes({ page: 1, limit: 100 });
      setItems(res?.data || []);
    } catch {
      toast.error("No se pudieron cargar relojes");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { load(); }, []);

  const updateField = (k, v) => setForm((p) => ({ ...p, [k]: v }));

  const reset = () => {
    setForm(emptyForm());
    setEditingId(null);
  };

  const handleSave = async () => {
    if (!form.nombre.trim()) return toast.error("Nombre requerido");
    if (form.tipo_conexion === "API" && !form.url_base.trim()) return toast.error("URL base requerida para API");
    try {
      setSaving(true);
      const payload = {
        ...form,
        intervalo_polling_min:
          form.tipo_conexion === "API" && form.intervalo_polling_min !== ""
            ? Number(form.intervalo_polling_min)
            : undefined,
        protocolo_api: form.tipo_conexion === "API" ? form.protocolo_api : undefined,
        url_base: form.tipo_conexion === "API" ? form.url_base || undefined : undefined,
        api_key: form.tipo_conexion === "API" && form.api_key ? form.api_key : undefined,
        tipo_auth: form.tipo_conexion === "API" ? form.tipo_auth : undefined,
        formato_respuesta: form.tipo_conexion === "API" ? form.formato_respuesta : undefined,
        campo_documento: form.tipo_conexion === "API" ? form.campo_documento || undefined : undefined,
        campo_timestamp: form.tipo_conexion === "API" ? form.campo_timestamp || undefined : undefined,
      };
      if (editingId) {
        await actualizarReloj(editingId, payload);
        toast.success("Reloj actualizado");
      } else {
        await crearReloj(payload);
        toast.success("Reloj creado");
      }
      reset();
      load();
    } catch (e) {
      toast.error(e?.response?.data?.message || "Error al guardar reloj");
    } finally {
      setSaving(false);
    }
  };

  const handleEdit = (r) => {
    setEditingId(r.id);
    setForm({
      nombre: r.nombre || "",
      tipo_conexion: r.tipo_conexion || "PLANILLA",
      protocolo_api: r.protocolo_api || "GENERICO",
      url_base: r.url_base || "",
      api_key: "",
      tipo_auth: r.tipo_auth || "NONE",
      formato_respuesta: r.formato_respuesta || "JSON",
      campo_documento: r.campo_documento || "documento",
      campo_timestamp: r.campo_timestamp || "timestamp",
      intervalo_polling_min: r.intervalo_polling_min ?? "",
      activo: r.activo ?? true,
    });
  };

  const handleDelete = async (id) => {
    const ok = await confirm({
      title: "Eliminar reloj",
      message: "Si tiene marcaciones se desactivará para preservar trazabilidad. ¿Continuar?",
      confirmText: "Confirmar",
    });
    if (!ok) return;
    try {
      await eliminarReloj(id);
      toast.success("Operación completada");
      load();
    } catch (e) {
      toast.error(e?.response?.data?.message || "No se pudo eliminar");
    }
  };

  const preconfigurarHikvision = () => {
    setForm((p) => ({
      ...p,
      tipo_conexion: "API",
      protocolo_api: "HIKVISION_ISAPI",
      tipo_auth: "DIGEST",
      formato_respuesta: "JSON",
      campo_documento: "employeeNoString",
      campo_timestamp: "time",
      intervalo_polling_min: p.intervalo_polling_min || "5",
    }));
    toast.info("Campos preconfigurados para Hikvision. Completá URL (http://IP:80) y credencial usuario:password.");
  };

  const handleSync = async (id) => {
    try {
      await sincronizarReloj(id, {});
      toast.success("Sincronización ejecutada");
      load();
    } catch (e) {
      toast.error(e?.response?.data?.message || "No se pudo sincronizar");
    }
  };

  const esHik = form.protocolo_api === "HIKVISION_ISAPI";

  return (
    <>
      <FormPanel>
        <SectionTitle>
          <Icon icon="lucide:clock-3" />
          {editingId ? "Editar reloj marcador" : "Nuevo reloj marcador"}
        </SectionTitle>
        <FieldsGrid $cols={4}>
          <Field $span={2}>
            <label>Nombre *</label>
            <input value={form.nombre} onChange={(e) => updateField("nombre", e.target.value)} />
          </Field>
          <Field>
            <label>Tipo conexión</label>
            <input
              value={form.tipo_conexion}
              onChange={(e) => updateField("tipo_conexion", e.target.value === "API" ? "API" : "PLANILLA")}
              list="presentismo-tipo-conn"
            />
            <datalist id="presentismo-tipo-conn">
              <option value="PLANILLA" />
              <option value="API" />
            </datalist>
          </Field>
          <Field>
            <label>Activo</label>
            <input
              value={form.activo ? "SI" : "NO"}
              onChange={(e) => updateField("activo", e.target.value.toUpperCase() !== "NO")}
            />
          </Field>
          {form.tipo_conexion === "API" && (
            <>
              <Field $span={2}>
                <label>Protocolo</label>
                <input
                  value={form.protocolo_api}
                  onChange={(e) =>
                    updateField(
                      "protocolo_api",
                      e.target.value === "HIKVISION_ISAPI" ? "HIKVISION_ISAPI" : "GENERICO",
                    )
                  }
                  list="presentismo-protocolo"
                />
                <datalist id="presentismo-protocolo">
                  <option value="GENERICO" />
                  <option value="HIKVISION_ISAPI" />
                </datalist>
              </Field>
              <Field $span={2}>
                <label>&nbsp;</label>
                <FooterActionButton type="button" onClick={preconfigurarHikvision}>
                  <Icon icon="lucide:fingerprint" /> Preconfigurar Hikvision
                </FooterActionButton>
              </Field>
              <Field $span={2}>
                <label>URL base</label>
                <input
                  value={form.url_base}
                  placeholder={esHik ? "http://192.168.1.64:80" : "https://reloj.demo/api"}
                  onChange={(e) => updateField("url_base", e.target.value)}
                />
              </Field>
              <Field>
                <label>Tipo auth</label>
                <input
                  value={form.tipo_auth}
                  onChange={(e) => updateField("tipo_auth", e.target.value)}
                  list="presentismo-tipo-auth"
                />
                <datalist id="presentismo-tipo-auth">
                  <option value="NONE" />
                  <option value="BASIC" />
                  <option value="BEARER" />
                  <option value="API_KEY" />
                  <option value="DIGEST" />
                </datalist>
              </Field>
              <Field>
                <label>API key{esHik ? " (usuario:password)" : ""}</label>
                <input
                  value={form.api_key}
                  placeholder={esHik ? "admin:MiPassword" : ""}
                  onChange={(e) => updateField("api_key", e.target.value)}
                />
              </Field>
              <Field>
                <label>Formato respuesta</label>
                <input value={form.formato_respuesta} onChange={(e) => updateField("formato_respuesta", e.target.value)} />
              </Field>
              <Field>
                <label>Campo documento</label>
                <input
                  value={form.campo_documento}
                  placeholder={esHik ? "employeeNoString" : "documento"}
                  onChange={(e) => updateField("campo_documento", e.target.value)}
                />
              </Field>
              <Field>
                <label>Campo timestamp</label>
                <input
                  value={form.campo_timestamp}
                  placeholder={esHik ? "time" : "timestamp"}
                  onChange={(e) => updateField("campo_timestamp", e.target.value)}
                />
              </Field>
              <Field>
                <label>Intervalo polling (min)</label>
                <input
                  type="number"
                  min="5"
                  value={form.intervalo_polling_min}
                  onChange={(e) => updateField("intervalo_polling_min", e.target.value)}
                />
              </Field>
              {esHik && (
                <Field $span={4}>
                  <small style={{ color: "var(--text-secondary, #64748b)" }}>
                    Hikvision DS-K1T343MFWX: registrá a cada empleado en el reloj con su cédula como
                    nº de empleado. La sincronización usa AcsEvent (POST paginado) con Digest Auth.
                  </small>
                </Field>
              )}
            </>
          )}
        </FieldsGrid>
        <Footer>
          <FooterActionButton type="button" onClick={reset}>
            <Icon icon="lucide:eraser" /> Limpiar
          </FooterActionButton>
          <FooterActionButton type="button" $variant="primary" disabled={saving} onClick={handleSave}>
            <Icon icon="lucide:save" /> {saving ? "Guardando..." : "Guardar"}
          </FooterActionButton>
        </Footer>
      </FormPanel>

      <ListPanel>
        <ListBody>
          <SectionTitle>
            <Icon icon="lucide:list" />
            Relojes configurados
          </SectionTitle>
          {!loading && items.length === 0 ? (
            <RRHHEmptyState
              icon="lucide:clock-3"
              titulo="Todavía no configuraste ningún reloj"
              descripcion="Empezá creando un reloj tipo PLANILLA para importar marcaciones manualmente desde un CSV/XLSX, o un reloj tipo API para sincronizar automáticamente con un equipo biométrico cada N minutos."
              ctaLabel="Crear primer reloj"
              onCta={() => {
                reset();
                document.querySelector('input[value=""]')?.focus?.();
              }}
              guiaSeccion="presentismo"
            />
          ) : (
            <TableWrap>
              <table>
                <thead>
                  <tr>
                    <th>Nombre</th>
                    <th>Tipo</th>
                    <th>URL</th>
                    <th>Polling</th>
                    <th>Activo</th>
                    <th>Acciones</th>
                  </tr>
                </thead>
                <tbody>
                  {items.map((r) => (
                    <tr key={r.id}>
                      <td>{r.nombre}</td>
                      <td>
                        {r.tipo_conexion}
                        {r.protocolo_api === "HIKVISION_ISAPI" ? " · Hikvision" : ""}
                      </td>
                      <td>{r.url_base || "-"}</td>
                      <td>{r.intervalo_polling_min ?? "-"}</td>
                      <td>{r.activo ? "Sí" : "No"}</td>
                      <td>
                        <RowActions>
                          <Tooltip title="Editar">
                            <IconButton size="small" onClick={() => handleEdit(r)} sx={actionIconSx("primary.main")}>
                              <Icon icon="lucide:edit" width={16} />
                            </IconButton>
                          </Tooltip>
                          {r.tipo_conexion === "API" && (
                            <Tooltip title="Sincronizar ahora">
                              <IconButton size="small" onClick={() => handleSync(r.id)} sx={actionIconSx("info.main")}>
                                <Icon icon="lucide:refresh-cw" width={16} />
                              </IconButton>
                            </Tooltip>
                          )}
                          <Tooltip title="Eliminar / desactivar">
                            <IconButton size="small" onClick={() => handleDelete(r.id)} sx={actionIconSx("error.main")}>
                              <Icon icon="lucide:trash-2" width={16} />
                            </IconButton>
                          </Tooltip>
                        </RowActions>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </TableWrap>
          )}
        </ListBody>
      </ListPanel>
      {dialogs}
    </>
  );
}
