import { Icon } from "@iconify/react";
import { Alert, Box, Button, Checkbox, IconButton, Tooltip } from "@mui/material";
import { useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import {
  aprobarComisionRrhh,
  aprobarComisionesMasivoRrhh,
  getComisionesPendientes,
  getEmpleados,
  getVinculacionesComisiones,
  importarComisionesRrhh,
  rechazarComisionRrhh,
  vincularComisionEmpleado,
} from "../../api/rrhh.service";
import { useConfirmDialog } from "../../hooks/useConfirmDialog";
import { useSubmodulo } from "../../hooks/useSubmodulo";
import {
  Badge,
  Container,
  EmptyState,
  GhostButton,
  ListBody,
  ListPanel,
  RowActions,
  TableWrap,
  ToolBar,
} from "../ui/FormShell";
import { SearchableSelect } from "../ui/SearchableSelect";
import { RRHHGuia } from "./_shared/RRHHGuia";

const hoy = new Date();
const ANIO_OPTIONS = Array.from({ length: 6 }, (_, i) => {
  const y = hoy.getFullYear() - 2 + i;
  return { id: String(y), label: String(y) };
});
const MES_OPTIONS = [
  "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio",
  "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre",
].map((m, i) => ({ id: String(i + 1), label: m }));
const ESTADO_OPTIONS = [
  { id: "PENDIENTE", label: "Pendiente" },
  { id: "APROBADA", label: "Aprobada" },
  { id: "RECHAZADA", label: "Rechazada" },
  { id: "INCLUIDA_EN_LIQUIDACION", label: "Incluida en liquidación" },
];
const ORIGEN_LABEL = { SUPERVISOR: "Supervisor", VENDEDOR: "Vendedor", COBRADOR: "Cobrador" };
const fmtMonto = (v) => Number(v || 0).toLocaleString("es-PY");

export function ComisionesTab() {
  const { confirm, prompt, dialogs } = useConfirmDialog();
  const { hasAccess: usaComercial } = useSubmodulo("COB_COMISIONES");

  const [anio, setAnio] = useState(String(hoy.getFullYear()));
  const [mes, setMes] = useState(String(hoy.getMonth() + 1));
  const [estadoFiltro, setEstadoFiltro] = useState("");
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [importando, setImportando] = useState(false);
  const [seleccion, setSeleccion] = useState(() => new Set());
  // Vista: pool de comisiones | vinculación supervisor/vendedor → empleado
  const [vista, setVista] = useState("pool");
  const [empleados, setEmpleados] = useState([]);
  const [vinc, setVinc] = useState({ supervisores: [], vendedores: [] });
  const [vincLoading, setVincLoading] = useState(false);

  const empleadoOptions = useMemo(
    () => empleados.map((e) => ({
      id: e.id,
      label: `${e.numero_empleado ? e.numero_empleado + " — " : ""}${e.apellidos ?? ""}, ${e.nombres ?? ""}`.replace(/^ — /, ""),
    })),
    [empleados],
  );

  const cargarVinculaciones = async () => {
    try {
      setVincLoading(true);
      const [emps, v] = await Promise.all([
        getEmpleados({ estado: "ACTIVO", limit: 200 }),
        getVinculacionesComisiones(),
      ]);
      setEmpleados(emps?.data || emps || []);
      setVinc({ supervisores: v?.supervisores || [], vendedores: v?.vendedores || [] });
    } catch {
      toast.error("No se pudieron cargar las vinculaciones");
    } finally {
      setVincLoading(false);
    }
  };

  useEffect(() => { if (vista === "vinculacion") cargarVinculaciones(); /* eslint-disable-next-line */ }, [vista]);

  const handleVincular = async (tipo, id, empleadoId) => {
    try {
      await vincularComisionEmpleado(tipo, id, empleadoId || null);
      toast.success(empleadoId ? "Vinculado" : "Desvinculado");
      cargarVinculaciones();
    } catch (error) {
      toast.error(error?.response?.data?.message || "No se pudo vincular");
    }
  };

  const load = async () => {
    try {
      setLoading(true);
      const params = { periodo_anio: Number(anio), periodo_mes: Number(mes) };
      if (estadoFiltro) params.estado = estadoFiltro;
      const resp = await getComisionesPendientes(params);
      setData(Array.isArray(resp) ? resp : resp?.data || []);
      setSeleccion(new Set());
    } catch {
      toast.error("Error al cargar comisiones");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { load(); /* eslint-disable-next-line */ }, [anio, mes, estadoFiltro]);

  const seleccionables = useMemo(
    () => data.filter((c) => c.estado === "PENDIENTE" || c.estado === "RECHAZADA"),
    [data],
  );

  const handleImportar = async () => {
    try {
      setImportando(true);
      const r = await importarComisionesRrhh({ periodo_anio: Number(anio), periodo_mes: Number(mes) });
      toast.success(`Importadas: ${r.importadas} · Ya existentes: ${r.yaExistentes} · Sin vínculo: ${r.sinVinculo}`);
      if (r.sinVinculo > 0) {
        toast.warning(`${r.sinVinculo} comisión(es) sin empleado RRHH vinculado quedaron fuera. Vinculá el supervisor/vendedor con un empleado.`);
      }
      load();
    } catch (error) {
      toast.error(error?.response?.data?.message || "No se pudo importar");
    } finally {
      setImportando(false);
    }
  };

  const handleAprobar = async (c) => {
    try {
      await aprobarComisionRrhh(c.id);
      toast.success("Comisión aprobada");
      load();
    } catch (error) {
      toast.error(error?.response?.data?.message || "No se pudo aprobar");
    }
  };

  const handleRechazar = async (c) => {
    const motivo = await prompt({
      title: "Rechazar comisión",
      message: `${empleadoLabel(c)} · Gs. ${fmtMonto(c.monto_bruto)}`,
      label: "Motivo del rechazo",
      required: true,
      confirmText: "Rechazar",
      confirmColor: "warning",
    });
    if (motivo === null) return;
    try {
      await rechazarComisionRrhh(c.id, { motivo });
      toast.success("Comisión rechazada");
      load();
    } catch (error) {
      toast.error(error?.response?.data?.message || "No se pudo rechazar");
    }
  };

  const handleAprobarMasivo = async () => {
    const ids = [...seleccion];
    if (ids.length === 0) return toast.error("Seleccioná al menos una comisión");
    const ok = await confirm({
      title: "Aprobar comisiones",
      message: `Se aprobarán ${ids.length} comisión(es) seleccionada(s).`,
      confirmText: "Aprobar",
      confirmColor: "success",
    });
    if (!ok) return;
    try {
      const r = await aprobarComisionesMasivoRrhh(ids);
      toast.success(`${r.aprobadas} comisión(es) aprobadas`);
      load();
    } catch (error) {
      toast.error(error?.response?.data?.message || "No se pudieron aprobar");
    }
  };

  const toggleSel = (id) => setSeleccion((prev) => {
    const next = new Set(prev);
    next.has(id) ? next.delete(id) : next.add(id);
    return next;
  });
  const toggleTodos = () => setSeleccion((prev) =>
    prev.size === seleccionables.length ? new Set() : new Set(seleccionables.map((c) => c.id)),
  );

  const empleadoLabel = (c) =>
    `${c.empleado?.numero_empleado ? c.empleado.numero_empleado + " — " : ""}${c.empleado?.apellidos ?? ""}, ${c.empleado?.nombres ?? ""}`.replace(/^ — /, "").trim();

  return (
    <Container>
      <RRHHGuia seccion="comisiones" />

      {usaComercial && (
        <Box sx={{ display: "flex", gap: 1, mb: 1.5 }}>
          <Button size="small" variant={vista === "pool" ? "contained" : "outlined"}
            startIcon={<Icon icon="lucide:list-checks" width={16} />} onClick={() => setVista("pool")}>
            Pool de comisiones
          </Button>
          <Button size="small" variant={vista === "vinculacion" ? "contained" : "outlined"}
            startIcon={<Icon icon="lucide:link" width={16} />} onClick={() => setVista("vinculacion")}>
            Vinculación con empleados
          </Button>
        </Box>
      )}

      {vista === "vinculacion" && usaComercial ? (
        <ListPanel>
          <ListBody>
            <Alert severity="info" sx={{ mb: 1.5 }}>
              Asigná a cada supervisor / vendedor su <strong>empleado RRHH</strong>. Solo los vinculados aparecen al importar comisiones a la nómina.
            </Alert>
            {vincLoading ? (
              <EmptyState>Cargando…</EmptyState>
            ) : (
              <TableWrap>
                <table>
                  <thead>
                    <tr><th>Nombre</th><th>Rol comercial</th><th style={{ minWidth: 280 }}>Empleado RRHH vinculado</th></tr>
                  </thead>
                  <tbody>
                    {[
                      ...vinc.supervisores.map((s) => ({ ...s, _tipo: "supervisor", _rol: "Supervisor" })),
                      ...vinc.vendedores.map((v) => ({ ...v, _tipo: "vendedor", _rol: (v.tipo || "").toLowerCase() === "cobrador" ? "Cobrador" : "Vendedor" })),
                    ].map((row) => (
                      <tr key={`${row._tipo}-${row.id}`}>
                        <td>{[row.nombre, row.apellido].filter(Boolean).join(" ")}</td>
                        <td>{row._rol}</td>
                        <td>
                          <SearchableSelect options={empleadoOptions} value={row.empleado_id || ""}
                            onChange={(id) => handleVincular(row._tipo, row.id, id || null)}
                            placeholder="Sin vincular…" />
                        </td>
                      </tr>
                    ))}
                    {vinc.supervisores.length === 0 && vinc.vendedores.length === 0 && (
                      <tr><td colSpan={3}><EmptyState>No hay supervisores ni vendedores activos.</EmptyState></td></tr>
                    )}
                  </tbody>
                </table>
              </TableWrap>
            )}
          </ListBody>
        </ListPanel>
      ) : (
      <ListPanel>
        <ListBody>
          <ToolBar>
            <Box sx={{ minWidth: 120 }}>
              <SearchableSelect label="Año" options={ANIO_OPTIONS} value={anio}
                onChange={(id) => setAnio(id || String(hoy.getFullYear()))} clearable={false} />
            </Box>
            <Box sx={{ minWidth: 150 }}>
              <SearchableSelect label="Mes" options={MES_OPTIONS} value={mes}
                onChange={(id) => setMes(id || String(hoy.getMonth() + 1))} clearable={false} />
            </Box>
            <Box sx={{ minWidth: 200 }}>
              <SearchableSelect label="Estado" options={ESTADO_OPTIONS} value={estadoFiltro}
                onChange={(id) => setEstadoFiltro(id || "")} placeholder="Todos los estados" />
            </Box>
            <Tooltip title="Refrescar">
              <GhostButton onClick={load} disabled={loading}><Icon icon="lucide:refresh-cw" /></GhostButton>
            </Tooltip>
            <Box sx={{ flex: 1 }} />
            {seleccion.size > 0 && (
              <Button variant="contained" color="success" size="small"
                startIcon={<Icon icon="lucide:check-check" width={16} />} onClick={handleAprobarMasivo}>
                Aprobar {seleccion.size}
              </Button>
            )}
            {usaComercial && (
              <Button variant="contained" size="small" disabled={importando}
                startIcon={<Icon icon="lucide:download" width={16} />} onClick={handleImportar}>
                {importando ? "Importando…" : "Importar del comercial"}
              </Button>
            )}
          </ToolBar>

          {usaComercial ? (
            <Alert severity="info" sx={{ mb: 1.5 }}>
              Importá las comisiones de supervisores/vendedores del módulo comercial al pool de nómina, revisá y aprobá.
              Las <strong>aprobadas</strong> se incluyen automáticamente en la liquidación del período (afectan la base de IPS).
              Solo se importan supervisores/vendedores con <strong>empleado RRHH vinculado</strong>.
            </Alert>
          ) : (
            <Alert severity="info" sx={{ mb: 1.5 }}>
              El módulo comercial de Comisiones no está activo. Las comisiones propias podés cargarlas como concepto
              <strong> COMISION_VENTAS</strong> por Novedades o Planilla externa; las aprobadas afectan la base de IPS.
            </Alert>
          )}

          {loading ? (
            <EmptyState>Cargando…</EmptyState>
          ) : data.length === 0 ? (
            <EmptyState>
              No hay comisiones en el pool para {MES_OPTIONS[Number(mes) - 1]?.label} {anio}.
              {usaComercial && " Usá «Importar del comercial» para traerlas."}
            </EmptyState>
          ) : (
            <TableWrap>
              <table>
                <thead>
                  <tr>
                    <th style={{ width: 36 }}>
                      <Checkbox size="small" disabled={seleccionables.length === 0}
                        checked={seleccionables.length > 0 && seleccion.size === seleccionables.length}
                        indeterminate={seleccion.size > 0 && seleccion.size < seleccionables.length}
                        onChange={toggleTodos} />
                    </th>
                    <th>Empleado</th>
                    <th>Origen</th>
                    <th style={{ textAlign: "right" }}>Monto</th>
                    <th>Descripción</th>
                    <th>Estado</th>
                    <th style={{ textAlign: "center" }}>Acciones</th>
                  </tr>
                </thead>
                <tbody>
                  {data.map((c) => {
                    const revisable = c.estado === "PENDIENTE" || c.estado === "RECHAZADA";
                    return (
                      <tr key={c.id}>
                        <td>
                          <Checkbox size="small" disabled={!revisable}
                            checked={seleccion.has(c.id)} onChange={() => toggleSel(c.id)} />
                        </td>
                        <td>{empleadoLabel(c)}</td>
                        <td>{ORIGEN_LABEL[c.origen_tipo] ?? c.origen_tipo}</td>
                        <td style={{ textAlign: "right", fontFamily: "monospace", fontWeight: 600 }}>{fmtMonto(c.monto_bruto)}</td>
                        <td style={{ fontSize: "0.85rem" }}>{c.descripcion || "—"}</td>
                        <td><Badge $state={c.estado}>{c.estado.replace(/_/g, " ")}</Badge></td>
                        <td style={{ textAlign: "center" }}>
                          <RowActions>
                            {c.estado !== "APROBADA" && c.estado !== "INCLUIDA_EN_LIQUIDACION" && (
                              <Tooltip title="Aprobar">
                                <IconButton size="small" color="success" onClick={() => handleAprobar(c)}>
                                  <Icon icon="lucide:check" width={16} />
                                </IconButton>
                              </Tooltip>
                            )}
                            {c.estado !== "RECHAZADA" && c.estado !== "INCLUIDA_EN_LIQUIDACION" && (
                              <Tooltip title="Rechazar">
                                <IconButton size="small" color="error" onClick={() => handleRechazar(c)}>
                                  <Icon icon="lucide:x" width={16} />
                                </IconButton>
                              </Tooltip>
                            )}
                          </RowActions>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </TableWrap>
          )}
        </ListBody>
      </ListPanel>
      )}
      {dialogs}
    </Container>
  );
}
