import { Icon } from "@iconify/react";
import { IconButton, Tooltip } from "@mui/material";
import { useCallback, useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import {
  aprobarPermisoPresentismo,
  crearPermisoPresentismo,
  getEmpleadosPresentismo,
  getPermisosPresentismo,
  rechazarPermisoPresentismo,
} from "../../../api/rrhh-presentismo.service";
import { getLegajoEmpleado, getTiposLegajo } from "../../../api/rrhh-legajos.service";
import { useConfirmDialog } from "../../../hooks/useConfirmDialog";
import { actionIconSx } from "../_shared/actionIconSx";
import { RRHHEmptyState } from "../_shared/RRHHEmptyState";
import {
  EmptyState,
  Field,
  FieldsGrid,
  Footer,
  FooterActionButton,
  FormPanel,
  ListBody,
  ListPanel,
  RowActions,
  SectionTitle,
  TableWrap,
} from "../../ui/FormShell";
import { SearchableSelect } from "../../ui/SearchableSelect";
import { hoyISO } from "../../../utils/fecha";

const TIPO_PERMISO_OPTIONS = [
  { id: "JORNADA_COMPLETA", label: "Jornada completa" },
  { id: "TURNO", label: "Turno (bloque)" },
  { id: "SALIDA_ANTICIPADA", label: "Salida anticipada" },
  { id: "LLEGADA_TARDIA", label: "Llegada tardía" },
  { id: "AUSENCIA_TURNO", label: "Ausencia de turno" },
];

const TIPO_JUST_OPTIONS = [
  { id: "MEDICA", label: "Médica" },
  { id: "PERSONAL", label: "Personal" },
  { id: "FUERZA_MAYOR", label: "Fuerza mayor" },
  { id: "INSTITUCIONAL", label: "Institucional" },
  { id: "CLIMA", label: "Clima" },
  { id: "OTRO", label: "Otro" },
];

const ESTADO_LABEL = {
  PENDIENTE: "Pendiente",
  APROBADO: "Aprobado",
  RECHAZADO: "Rechazado",
};

const emptyForm = () => ({
  empleado_id: "",
  fecha: hoyISO(),
  tipo_permiso: "JORNADA_COMPLETA",
  turno_bloque_orden: "",
  hora_desde: "",
  hora_hasta: "",
  minutos_tolerados: "",
  legajo_documento_id: "",
  motivo: "",
  tipo_justificacion: "PERSONAL",
  afecta_descuento: true,
});

const empleadoLabel = (e) => `${e.numero_empleado} — ${e.apellidos}, ${e.nombres}`;

export function PermisosPresentismoTab() {
  const { confirm, dialogs } = useConfirmDialog();
  const [form, setForm] = useState(emptyForm());
  const [empleados, setEmpleados] = useState([]);
  const [permisos, setPermisos] = useState([]);
  const [documentosLegajo, setDocumentosLegajo] = useState([]);
  const [tipoCertMedId, setTipoCertMedId] = useState("");
  const [loading, setLoading] = useState(false);

  const requiresBloque = useMemo(
    () => form.tipo_permiso === "TURNO" || form.tipo_permiso === "AUSENCIA_TURNO",
    [form.tipo_permiso],
  );

  const requiresMinutos = useMemo(
    () => form.tipo_permiso === "LLEGADA_TARDIA",
    [form.tipo_permiso],
  );

  const loadEmpleados = async () => {
    try {
      const res = await getEmpleadosPresentismo({ page: 1, limit: 200, estado: "ACTIVO" });
      setEmpleados(res?.data || []);
    } catch (e) {
      toast.error(e?.response?.data?.message || "No se pudieron cargar empleados");
    }
  };

  const loadPermisos = async () => {
    try {
      setLoading(true);
      const res = await getPermisosPresentismo({ page: 1, limit: 200 });
      setPermisos(res?.data || []);
    } catch (e) {
      toast.error(e?.response?.data?.message || "No se pudieron cargar permisos");
    } finally {
      setLoading(false);
    }
  };

  const loadCatalogoLegajos = async () => {
    try {
      const tipos = await getTiposLegajo({ incluir_inactivos: false });
      const cert = (tipos?.data || []).find((t) => t.codigo === "CERTIFICADO_MED");
      setTipoCertMedId(cert?.id || "");
    } catch {
      setTipoCertMedId("");
    }
  };

  const loadDocsLegajo = useCallback(async (empleadoId, justificacion) => {
    if (!empleadoId) {
      setDocumentosLegajo([]);
      return;
    }
    try {
      const params = {};
      if (justificacion === "MEDICA" && tipoCertMedId) {
        params.tipo_documento_id = tipoCertMedId;
      }
      const res = await getLegajoEmpleado(empleadoId, params);
      const docs = Array.isArray(res) ? res : res?.data || [];
      setDocumentosLegajo(docs);
    } catch {
      setDocumentosLegajo([]);
    }
  }, [tipoCertMedId]);

  useEffect(() => {
    loadEmpleados();
    loadPermisos();
    loadCatalogoLegajos();
  }, []);

  useEffect(() => {
    loadDocsLegajo(form.empleado_id, form.tipo_justificacion);
  }, [form.empleado_id, form.tipo_justificacion, loadDocsLegajo]);

  const onSubmit = async () => {
    if (!form.empleado_id) return toast.error("Empleado obligatorio");
    if (!form.fecha) return toast.error("Fecha obligatoria");
    if (!form.motivo.trim()) return toast.error("Motivo obligatorio");
    if (requiresBloque && !form.turno_bloque_orden) {
      return toast.error("El tipo seleccionado requiere turno/bloque");
    }
    if (requiresMinutos && !form.minutos_tolerados) {
      return toast.error("La llegada tardía requiere minutos tolerados");
    }

    try {
      await crearPermisoPresentismo({
        empleado_id: form.empleado_id,
        fecha: form.fecha,
        tipo_permiso: form.tipo_permiso,
        turno_bloque_orden: requiresBloque ? Number(form.turno_bloque_orden) : undefined,
        hora_desde: form.hora_desde || undefined,
        hora_hasta: form.hora_hasta || undefined,
        minutos_tolerados: requiresMinutos ? Number(form.minutos_tolerados) : undefined,
        legajo_documento_id: form.legajo_documento_id || undefined,
        motivo: form.motivo,
        tipo_justificacion: form.tipo_justificacion,
        afecta_descuento: Boolean(form.afecta_descuento),
      });
      toast.success("Permiso creado en estado PENDIENTE");
      setForm((prev) => ({ ...emptyForm(), empleado_id: prev.empleado_id }));
      loadPermisos();
    } catch (e) {
      toast.error(e?.response?.data?.message || "No se pudo crear el permiso");
    }
  };

  const onAprobar = async (permiso) => {
    const ok = await confirm({
      title: "Aprobar permiso",
      message: "¿Confirmás aprobar este permiso de presentismo?",
      confirmText: "Aprobar",
    });
    if (!ok) return;

    try {
      await aprobarPermisoPresentismo(permiso.id, {});
      toast.success("Permiso aprobado");
      loadPermisos();
    } catch (e) {
      toast.error(e?.response?.data?.message || "No se pudo aprobar");
    }
  };

  const onRechazar = async (permiso) => {
    const ok = await confirm({
      title: "Rechazar permiso",
      message: "¿Confirmás rechazar este permiso de presentismo?",
      confirmText: "Rechazar",
      confirmColor: "error",
    });
    if (!ok) return;

    try {
      await rechazarPermisoPresentismo(permiso.id, {});
      toast.success("Permiso rechazado");
      loadPermisos();
    } catch (e) {
      toast.error(e?.response?.data?.message || "No se pudo rechazar");
    }
  };

  return (
    <>
      <FormPanel>
        <SectionTitle><Icon icon="lucide:file-check-2" /> Nuevo permiso de presentismo</SectionTitle>
        <FieldsGrid $cols={4}>
          <Field $span={2}>
            <label>Empleado</label>
            <SearchableSelect
              options={empleados}
              value={form.empleado_id}
              onChange={(id) =>
                setForm((p) => ({ ...p, empleado_id: id || "", legajo_documento_id: "" }))
              }
              getOptionLabel={empleadoLabel}
              placeholder="Buscar empleado"
            />
          </Field>
          <Field>
            <label>Fecha</label>
            <input type="date" value={form.fecha} onChange={(e) => setForm((p) => ({ ...p, fecha: e.target.value }))} />
          </Field>
          <Field>
            <label>Tipo de permiso</label>
            <SearchableSelect
              options={TIPO_PERMISO_OPTIONS}
              value={form.tipo_permiso}
              onChange={(id) => setForm((p) => ({ ...p, tipo_permiso: id || "JORNADA_COMPLETA" }))}
              clearable={false}
            />
          </Field>
          {requiresBloque && (
            <Field>
              <label>Bloque del turno</label>
              <input type="number" min="1" value={form.turno_bloque_orden} onChange={(e) => setForm((p) => ({ ...p, turno_bloque_orden: e.target.value }))} />
            </Field>
          )}
          <Field>
            <label>Hora desde (opcional)</label>
            <input type="time" value={form.hora_desde} onChange={(e) => setForm((p) => ({ ...p, hora_desde: e.target.value }))} />
          </Field>
          <Field>
            <label>Hora hasta (opcional)</label>
            <input type="time" value={form.hora_hasta} onChange={(e) => setForm((p) => ({ ...p, hora_hasta: e.target.value }))} />
          </Field>
          {requiresMinutos && (
            <Field>
              <label>Minutos tolerados</label>
              <input type="number" min="1" value={form.minutos_tolerados} onChange={(e) => setForm((p) => ({ ...p, minutos_tolerados: e.target.value }))} />
            </Field>
          )}
          <Field>
            <label>Justificación</label>
            <SearchableSelect
              options={TIPO_JUST_OPTIONS}
              value={form.tipo_justificacion}
              onChange={(id) =>
                setForm((p) => ({
                  ...p,
                  tipo_justificacion: id || "PERSONAL",
                  legajo_documento_id: "",
                }))
              }
              clearable={false}
            />
          </Field>
          <Field>
            <label>Documento legajo (opcional)</label>
            <SearchableSelect
              options={documentosLegajo.map((d) => ({
                id: d.id,
                label: `${d.tipo_documento?.codigo || "DOC"} — ${d.nombre_original}`,
              }))}
              value={form.legajo_documento_id}
              onChange={(id) => setForm((p) => ({ ...p, legajo_documento_id: id || "" }))}
              placeholder={
                form.tipo_justificacion === "MEDICA"
                  ? "Certificado médico del legajo"
                  : "Documento del legajo"
              }
            />
          </Field>
          <Field $span={2}>
            <label>Motivo</label>
            <input value={form.motivo} onChange={(e) => setForm((p) => ({ ...p, motivo: e.target.value }))} />
          </Field>
          <Field>
            <label>Afecta descuento</label>
            <input
              value={form.afecta_descuento ? "SI" : "NO"}
              onChange={(e) => setForm((p) => ({ ...p, afecta_descuento: e.target.value.toUpperCase() !== "NO" }))}
            />
          </Field>
        </FieldsGrid>
        <Footer>
          <FooterActionButton type="button" onClick={() => setForm(emptyForm())}>
            <Icon icon="lucide:eraser" /> Limpiar
          </FooterActionButton>
          <FooterActionButton type="button" $variant="primary" onClick={onSubmit}>
            <Icon icon="lucide:save" /> Guardar permiso
          </FooterActionButton>
        </Footer>
      </FormPanel>

      <ListPanel>
        <ListBody>
          <SectionTitle><Icon icon="lucide:list-checks" /> Permisos</SectionTitle>
          {loading ? (
            <EmptyState>Cargando...</EmptyState>
          ) : permisos.length === 0 ? (
            <RRHHEmptyState
              icon="lucide:file-clock"
              titulo="Sin permisos cargados"
              descripcion="Creá permisos para gestionar excepciones de jornada, tardanzas y ausencias por turno."
              guiaSeccion="presentismo"
            />
          ) : (
            <TableWrap>
              <table>
                <thead>
                  <tr>
                    <th>Empleado</th>
                    <th>Fecha</th>
                    <th>Tipo</th>
                    <th>Detalle</th>
                    <th>Doc legajo</th>
                    <th>Estado</th>
                    <th>Acciones</th>
                  </tr>
                </thead>
                <tbody>
                  {permisos.map((p) => (
                    <tr key={p.id}>
                      <td>{p.empleado ? `${p.empleado.numero_empleado} — ${p.empleado.apellidos}, ${p.empleado.nombres}` : "Empleado no disponible"}</td>
                      <td>{String(p.fecha).slice(0, 10)}</td>
                      <td>{p.tipo_permiso}</td>
                      <td>
                        {p.turno_bloque_orden ? `Bloque ${p.turno_bloque_orden} · ` : ""}
                        {p.hora_desde && p.hora_hasta ? `${p.hora_desde}-${p.hora_hasta} · ` : ""}
                        {p.minutos_tolerados ? `${p.minutos_tolerados} min` : ""}
                      </td>
                      <td>{p.legajo_documento?.nombre_original || "-"}</td>
                      <td>{ESTADO_LABEL[p.estado] || p.estado}</td>
                      <td>
                        {p.estado === "PENDIENTE" ? (
                          <RowActions>
                            <Tooltip title="Aprobar">
                              <IconButton size="small" onClick={() => onAprobar(p)} sx={actionIconSx("success.main")}>
                                <Icon icon="lucide:check" width={16} />
                              </IconButton>
                            </Tooltip>
                            <Tooltip title="Rechazar">
                              <IconButton size="small" onClick={() => onRechazar(p)} sx={actionIconSx("error.main")}>
                                <Icon icon="lucide:x" width={16} />
                              </IconButton>
                            </Tooltip>
                          </RowActions>
                        ) : (
                          "-"
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </TableWrap>
          )}
        </ListBody>
      </ListPanel>
      {dialogs}
    </>
  );
}
