import { Icon } from "@iconify/react";
import { Alert, IconButton, Tooltip, Typography } from "@mui/material";
import { useCallback, useEffect, useState } from "react";
import { toast } from "sonner";
import {
  actualizarConcepto,
  crearConcepto,
  eliminarConcepto,
  getConceptos,
  sembrarRrhhDefaults,
} from "../../api/rrhh.service";
import { useConfirmDialog } from "../../hooks/useConfirmDialog";
import { RRHHGuia } from "./_shared/RRHHGuia";
import { RRHHEmptyState } from "./_shared/RRHHEmptyState";
import { useRRHHContext } from "./_shared/RRHHContext";
import {
  Badge,
  Container,
  EmptyState,
  Field,
  FieldsGrid,
  FormHead,
  FormPanel,
  Footer,
  FooterActionButton,
  GhostButton,
  ListBody,
  ListPanel,
  RowActions,
  SectionTitle,
  TableWrap,
} from "../ui/FormShell";

const TIPOS = [
  { value: "INGRESO", label: "Ingreso" },
  { value: "EGRESO", label: "Egreso" },
];

const CATEGORIAS = [
  "SALARIO", "IPS", "HORA_EXTRA", "SUBSIDIO",
  "ANTICIPO", "DESCUENTO", "COMISION", "BONO", "OTRO",
];

const APLICA_A = [
  { value: "TODOS", label: "Todos" },
  { value: "MENSUAL", label: "Mensual" },
  { value: "JORNAL", label: "Jornal" },
  { value: "COMISION", label: "Comisionistas" },
];

const EMPTY = {
  codigo: "",
  nombre: "",
  tipo: "INGRESO",
  categoria: "SALARIO",
  afecta_base_ips: false,
  afecta_base_aguinaldo: false,
  es_porcentaje: false,
  porcentaje: "",
  es_fijo: false,
  aplica_a: "TODOS",
  orden_visualizacion: 0,
  activo: true,
};

export function ConceptosTab() {
  const { reloadPrereqs } = useRRHHContext();
  const { confirm, dialogs } = useConfirmDialog();
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [seeding, setSeeding] = useState(false);
  const [search] = useState("");
  const [tipoFiltro] = useState("");
  const [editingId, setEditingId] = useState(null);
  const [form, setForm] = useState(EMPTY);

  const load = useCallback(async () => {
    try {
      setLoading(true);
      const params = {};
      if (search) params.search = search;
      if (tipoFiltro) params.tipo = tipoFiltro;
      setData(await getConceptos(params));
    } catch {
      toast.error("Error al cargar conceptos");
    } finally {
      setLoading(false);
    }
  }, [search, tipoFiltro]);

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

  const handleSeed = async () => {
    try {
      setSeeding(true);
      const resp = await sembrarRrhhDefaults();
      const c = resp?.conceptos || {};
      const p = resp?.parametros || {};
      toast.success(
        `Sembrados: ${c.creados || 0} conceptos nuevos, ${p.creados || 0} parámetros nuevos`,
      );
      load();
      reloadPrereqs();
    } catch (error) {
      toast.error(error?.response?.data?.message || "Error al sembrar valores por defecto");
    } finally {
      setSeeding(false);
    }
  };

  const handleGuardar = async () => {
    if (!form.codigo.trim() || !form.nombre.trim()) {
      return toast.error("Código y nombre son requeridos");
    }
    if (form.es_porcentaje && (form.porcentaje === "" || Number.isNaN(Number(form.porcentaje)))) {
      return toast.error("Indicá el porcentaje (ej: 0.09 para 9%)");
    }
    try {
      const payload = {
        ...form,
        porcentaje: form.es_porcentaje && form.porcentaje !== "" ? Number(form.porcentaje) : undefined,
        orden_visualizacion: Number(form.orden_visualizacion) || 0,
      };
      if (editingId) {
        await actualizarConcepto(editingId, payload);
        toast.success("Concepto actualizado");
      } else {
        await crearConcepto(payload);
        toast.success("Concepto creado");
      }
      setForm(EMPTY);
      setEditingId(null);
      load();
      reloadPrereqs();
    } catch (error) {
      toast.error(error?.response?.data?.message || "Error al guardar concepto");
    }
  };

  const handleEditar = (c) => {
    setEditingId(c.id);
    setForm({
      codigo: c.codigo || "",
      nombre: c.nombre || "",
      tipo: c.tipo || "INGRESO",
      categoria: c.categoria || "SALARIO",
      afecta_base_ips: !!c.afecta_base_ips,
      afecta_base_aguinaldo: !!c.afecta_base_aguinaldo,
      es_porcentaje: !!c.es_porcentaje,
      porcentaje: c.porcentaje ?? "",
      es_fijo: !!c.es_fijo,
      aplica_a: c.aplica_a || "TODOS",
      orden_visualizacion: c.orden_visualizacion ?? 0,
      activo: c.activo ?? true,
    });
  };

  const handleEliminar = async (c) => {
    if (c.es_del_sistema) {
      return toast.error("Los conceptos del sistema no se pueden eliminar (sí desactivar)");
    }
    const ok = await confirm({
      title: "Eliminar concepto",
      message: `¿Eliminar concepto "${c.nombre}"?`,
      confirmText: "Eliminar",
      confirmColor: "error",
    });
    if (!ok) return;
    try {
      await eliminarConcepto(c.id);
      toast.success("Concepto eliminado");
      load();
      reloadPrereqs();
    } catch (error) {
      toast.error(error?.response?.data?.message || "No se pudo eliminar");
    }
  };

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

  return (
    <Container>
      <RRHHGuia seccion="conceptos" />
      {data.length === 0 && !loading && (
        <Alert
          severity="info"
          icon={<Icon icon="lucide:sparkles" width={18} />}
          action={
            <FooterActionButton type="button" $variant="primary" disabled={seeding} onClick={handleSeed}>
              <Icon icon="lucide:sparkles" /> {seeding ? "Sembrando..." : "Sembrar defaults"}
            </FooterActionButton>
          }
        >
          <Typography variant="body2" sx={{ fontWeight: 600 }}>
            No hay conceptos cargados todavía
          </Typography>
          <Typography variant="caption">
            Podemos sembrar los conceptos del sistema (SALARIO_BASE, IPS_OBRERO, HORAS_EXTRA, etc.) y los parámetros legales (IPS %, SMLV) automáticamente.
          </Typography>
        </Alert>
      )}

      <FormPanel>
        <FormHead>
          <SectionTitle>
            <Icon icon={editingId ? "lucide:edit-3" : "lucide:plus-circle"} />
            {editingId ? "Editar concepto" : "Nuevo concepto"}
          </SectionTitle>
          {editingId && (
            <GhostButton onClick={() => { setForm(EMPTY); setEditingId(null); }}>
              <Icon icon="lucide:x" /> Cancelar edición
            </GhostButton>
          )}
        </FormHead>

        <FieldsGrid $cols={4}>
          <Field>
            <label>Código *</label>
            <input value={form.codigo}
              onChange={(e) => updateField("codigo", e.target.value)} />
          </Field>
          <Field $span={2}>
            <label>Nombre *</label>
            <input value={form.nombre}
              onChange={(e) => updateField("nombre", e.target.value)} />
          </Field>
          <Field>
            <label>Orden</label>
            <input type="number" min="0" value={form.orden_visualizacion}
              onChange={(e) => updateField("orden_visualizacion", e.target.value)} />
          </Field>

          <Field>
            <label>Tipo *</label>
            <select value={form.tipo}
              onChange={(e) => updateField("tipo", e.target.value)}>
              {TIPOS.map((t) => <option key={t.value} value={t.value}>{t.label}</option>)}
            </select>
          </Field>
          <Field>
            <label>Categoría *</label>
            <select value={form.categoria}
              onChange={(e) => updateField("categoria", e.target.value)}>
              {CATEGORIAS.map((c) => <option key={c} value={c}>{c}</option>)}
            </select>
          </Field>
          <Field>
            <label>Aplica a</label>
            <select value={form.aplica_a}
              onChange={(e) => updateField("aplica_a", e.target.value)}>
              {APLICA_A.map((a) => <option key={a.value} value={a.value}>{a.label}</option>)}
            </select>
          </Field>
          <Field>
            <label>Activo</label>
            <select value={form.activo ? "true" : "false"}
              onChange={(e) => updateField("activo", e.target.value === "true")}>
              <option value="true">Activo</option>
              <option value="false">Inactivo</option>
            </select>
          </Field>

          <Field $span={2}>
            <label>Banderas</label>
            <div style={{ display: "flex", gap: 14, alignItems: "center", flexWrap: "wrap", paddingTop: 6 }}>
              <Tooltip
                enterDelay={300}
                title={`Incluye este concepto en la base sobre la que se calcula el IPS. Si es un INGRESO (comisión, viático gravado, bonificación) suma a la base; si es un EGRESO marcado, resta. El IPS se calcula sobre el neto resultante.${
                  form.tipo === "EGRESO" ? " Como este concepto es EGRESO, restará de la base IPS." : " Como este concepto es INGRESO, sumará a la base IPS."
                }`}
              >
                <label style={{ textTransform: "none", letterSpacing: 0, fontSize: "0.85rem", display: "inline-flex", gap: 6, alignItems: "center", cursor: "help" }}>
                  <input type="checkbox" checked={form.afecta_base_ips}
                    onChange={(e) => updateField("afecta_base_ips", e.target.checked)} />
                  Afecta base IPS
                  <Icon icon="lucide:info" style={{ fontSize: "0.9rem", opacity: 0.55 }} />
                </label>
              </Tooltip>
              <Tooltip
                enterDelay={300}
                title="Incluye este concepto en la base del aguinaldo (1/12 de las remuneraciones brutas del año, Art. 243 CT)."
              >
                <label style={{ textTransform: "none", letterSpacing: 0, fontSize: "0.85rem", display: "inline-flex", gap: 6, alignItems: "center", cursor: "help" }}>
                  <input type="checkbox" checked={form.afecta_base_aguinaldo}
                    onChange={(e) => updateField("afecta_base_aguinaldo", e.target.checked)} />
                  Afecta aguinaldo
                  <Icon icon="lucide:info" style={{ fontSize: "0.9rem", opacity: 0.55 }} />
                </label>
              </Tooltip>
              <label style={{ textTransform: "none", letterSpacing: 0, fontSize: "0.85rem", display: "inline-flex", gap: 6, alignItems: "center" }}>
                <input type="checkbox" checked={form.es_fijo}
                  onChange={(e) => updateField("es_fijo", e.target.checked)} />
                Monto fijo
              </label>
              <label style={{ textTransform: "none", letterSpacing: 0, fontSize: "0.85rem", display: "inline-flex", gap: 6, alignItems: "center" }}>
                <input type="checkbox" checked={form.es_porcentaje}
                  onChange={(e) => updateField("es_porcentaje", e.target.checked)} />
                Es porcentaje
              </label>
            </div>
            <Typography variant="caption" sx={{ color: "text.secondary", mt: 0.75, display: "block", lineHeight: 1.4 }}>
              <strong>Afecta base IPS:</strong> marcá esta casilla para que el concepto entre en el cálculo del IPS.
              Los ingresos (comisiones, viáticos gravados) suman a la base y los egresos marcados restan; el aporte
              se calcula sobre el neto.
            </Typography>
          </Field>
          <Field $span={2}>
            <label>Porcentaje (decimal: 0.09 = 9%)</label>
            <input type="number" step="0.0001" min="0" max="10"
              value={form.porcentaje} disabled={!form.es_porcentaje}
              onChange={(e) => updateField("porcentaje", e.target.value)} />
          </Field>
        </FieldsGrid>

        <Footer>
          <FooterActionButton type="button" $variant="primary" onClick={handleGuardar}>
            <Icon icon={editingId ? "lucide:check-circle" : "lucide:plus"} />
            {editingId ? "Actualizar concepto" : "Crear concepto"}
          </FooterActionButton>
        </Footer>
      </FormPanel>

      <ListPanel>
        <ListBody>
          <SectionTitle>
            <Icon icon="lucide:list" /> Conceptos registrados
          </SectionTitle>

          {loading ? (
            <EmptyState>Cargando...</EmptyState>
          ) : data.length === 0 ? (
            <RRHHEmptyState
              icon="lucide:scroll-text"
              titulo="Sin conceptos registrados"
              descripcion="Los conceptos definen los rubros de la liquidación: haberes (sueldo, horas extra, bonificaciones) y descuentos (IPS, adelantos, etc.). Usá el botón «Sembrar defaults» para cargar los conceptos legales estándar."
              guiaSeccion="conceptos"
            />
          ) : (
            <TableWrap>
              <table>
                <thead>
                  <tr>
                    <th>Código</th>
                    <th>Nombre</th>
                    <th>Tipo</th>
                    <th>Categoría</th>
                    <th style={{ textAlign: "right" }}>%</th>
                    <th style={{ textAlign: "center" }}>IPS</th>
                    <th style={{ textAlign: "center" }}>Aguin.</th>
                    <th>Estado</th>
                    <th style={{ textAlign: "center" }}>Acciones</th>
                  </tr>
                </thead>
                <tbody>
                  {data.map((c) => (
                    <tr key={c.id}>
                      <td>
                        {c.codigo}
                        {c.es_del_sistema && (
                          <Icon icon="lucide:lock" width={12} style={{ marginLeft: 6, opacity: 0.6 }} />
                        )}
                      </td>
                      <td>{c.nombre}</td>
                      <td>
                        <Badge $state={c.tipo === "INGRESO" ? "ACTIVO" : "ANULADA"}>
                          {c.tipo}
                        </Badge>
                      </td>
                      <td>{c.categoria}</td>
                      <td style={{ textAlign: "right" }}>
                        {c.es_porcentaje && c.porcentaje != null
                          ? `${(Number(c.porcentaje) * 100).toFixed(2)}%`
                          : "-"}
                      </td>
                      <td style={{ textAlign: "center" }}>{c.afecta_base_ips ? "✓" : "—"}</td>
                      <td style={{ textAlign: "center" }}>{c.afecta_base_aguinaldo ? "✓" : "—"}</td>
                      <td>
                        <Badge $state={c.activo ? "ACTIVO" : "INACTIVO"}>
                          {c.activo ? "Activo" : "Inactivo"}
                        </Badge>
                      </td>
                      <td style={{ textAlign: "center" }}>
                        <RowActions>
                          <Tooltip title="Editar">
                            <IconButton size="small" onClick={() => handleEditar(c)}>
                              <Icon icon="lucide:pencil" width={16} />
                            </IconButton>
                          </Tooltip>
                          <Tooltip title={c.es_del_sistema ? "Concepto del sistema (no eliminable)" : "Eliminar"}>
                            <span>
                              <IconButton size="small" color="error"
                                disabled={c.es_del_sistema}
                                onClick={() => handleEliminar(c)}>
                                <Icon icon="lucide:trash-2" width={16} />
                              </IconButton>
                            </span>
                          </Tooltip>
                        </RowActions>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </TableWrap>
          )}
        </ListBody>
      </ListPanel>
      {dialogs}
    </Container>
  );
}
