import { Icon } from "@iconify/react";
import {
  Alert,
  Box,
  IconButton,
  InputAdornment,
  Skeleton,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { Fragment, useEffect, useMemo, useState } from "react";
import { useSearchParams } from "react-router-dom";
import { toast } from "sonner";
import {
  actualizarEmpleado,
  crearEmpleado,
  eliminarEmpleado,
  getBancosRrhh,
  getCargos,
  getCentrosCosto,
  getDepartamentos,
  getEmpleados,
  getTiposEmpleado,
} from "../../api/rrhh.service";
import { getSucursales } from "../../api/sucursales.service";
import {
  Badge,
  Container,
  Divider,
  EmptyState,
  Field,
  FieldsGrid,
  FormHead,
  FormPanel,
  Footer,
  FooterActionButton,
  GhostButton,
  ListBody,
  ListPanel,
  RowActions,
  SectionTitle,
  TableWrap,
  ToolBar,
} from "../ui/FormShell";
import { TablePaginationBar } from "../_standards";
import { SearchableSelect } from "../ui/SearchableSelect";
import { useConfirmDialog } from "../../hooks/useConfirmDialog";
import { RRHHGuia } from "./_shared/RRHHGuia";
import { useRRHHContext } from "./_shared/RRHHContext";
import { MonedaInput } from "../common/MonedaInput";
import { RRHHPrereqChecklist } from "./_shared/RRHHPrereqChecklist";
import { InlineValidationBanner } from "./_shared/InlineValidationBanner";
import { fmtFechaCalendario, hoyISO } from "../../utils/fecha";

const SEXO_OPTIONS = [
  { id: "M", label: "Masculino" },
  { id: "F", label: "Femenino" },
  { id: "O", label: "Otro" },
];
const ESTADO_CIVIL_OPTIONS = [
  { id: "SOLTERO", label: "Soltero/a" },
  { id: "CASADO", label: "Casado/a" },
  { id: "DIVORCIADO", label: "Divorciado/a" },
  { id: "VIUDO", label: "Viudo/a" },
  { id: "UNION_LIBRE", label: "Unión libre" },
];
const TIPO_SALARIO_OPTIONS = [
  { id: "MENSUAL", label: "Mensual" },
  { id: "JORNAL", label: "Jornal" },
  { id: "COMISION", label: "Comisión" },
];
const REGIMEN_IPS_OPTIONS = [
  { id: "GENERAL", label: "General (9%)" },
  { id: "MICROEMPRESA_80", label: "Microempresa (80%)" },
  { id: "DOMESTICO", label: "Doméstico" },
  { id: "EXENTO", label: "Exento" },
];
const TIPO_CUENTA_OPTIONS = [
  { id: "CAJA_AHORRO", label: "Caja de ahorro" },
  { id: "CUENTA_CORRIENTE", label: "Cuenta corriente" },
];
const ESTADO_FILTRO_OPTIONS = [
  { id: "ACTIVO", label: "Activo" },
  { id: "INACTIVO", label: "Inactivo" },
  { id: "LICENCIA", label: "Licencia" },
  { id: "SUSPENDIDO", label: "Suspendido" },
  { id: "EGRESADO", label: "Egresado" },
];
const sucursalLabel = (s) => s.descripcion || s.codigo || "Sin nombre";
const cargoLabel = (c) => (c.codigo ? `${c.codigo} — ${c.nombre}` : c.nombre);
const departamentoLabel = (d) => (d.codigo ? `${d.codigo} — ${d.nombre}` : d.nombre);
const ccLabel = (cc) => `${cc.codigo} — ${cc.nombre}`;
const tipoEmpleadoLabel = (t) => `${t.codigo} — ${t.nombre}`;

const EMPTY_FORM = {
  numero_empleado: "",
  nombres: "",
  apellidos: "",
  cedula_identidad: "",
  ruc: "",
  fecha_nacimiento: "",
  sexo: "M",
  estado_civil: "SOLTERO",
  cantidad_hijos: 0,
  email: "",
  telefono: "",
  direccion: "",
  sucursal_id: "",
  departamento_id: "",
  cargo_id: "",
  centro_costo_id: "",
  tipo_empleado_id: "",
  fecha_ingreso: hoyISO(),
  fecha_egreso: "",
  salario_base: 0,
  tipo_salario: "MENSUAL",
  banco_id: "",
  cuenta_bancaria: "",
  tipo_cuenta: "",
  numero_ips: "",
  regimen_ips: "GENERAL",
  observaciones: "",
};

const labelDe = (options, id, fallback = "—") =>
  options.find((o) => o.id === id)?.label || fallback;

function DetalleItem({ label, value }) {
  return (
    <Box>
      <Typography variant="caption" sx={{ color: "text.disabled", display: "block", lineHeight: 1.2 }}>
        {label}
      </Typography>
      <Typography variant="body2" sx={{ fontWeight: 500 }}>
        {value || "—"}
      </Typography>
    </Box>
  );
}

function DetalleGrupo({ icon, titulo, children }) {
  return (
    <Box sx={{ flex: "1 1 240px", minWidth: 220 }}>
      <Box sx={{ display: "flex", alignItems: "center", gap: 0.75, mb: 1.25, color: "text.secondary" }}>
        <Icon icon={icon} width={16} />
        <Typography variant="subtitle2" sx={{ fontWeight: 700, letterSpacing: 0.3 }}>
          {titulo}
        </Typography>
      </Box>
      <Box sx={{ display: "grid", gap: 1.25 }}>{children}</Box>
    </Box>
  );
}

function EmpleadoDetalle({ emp }) {
  const salario = Number(emp.salario_base || 0).toLocaleString("es-PY");
  return (
    <Box sx={{ p: 2.5, display: "flex", flexWrap: "wrap", gap: 3 }}>
      <DetalleGrupo icon="lucide:contact" titulo="CONTACTO">
        <DetalleItem label="Email" value={emp.email} />
        <DetalleItem label="Teléfono" value={emp.telefono} />
        <DetalleItem label="Dirección" value={emp.direccion} />
        <DetalleItem label="RUC" value={emp.ruc} />
      </DetalleGrupo>

      <DetalleGrupo icon="lucide:user" titulo="PERSONAL">
        <DetalleItem label="Sexo" value={labelDe(SEXO_OPTIONS, emp.sexo)} />
        <DetalleItem label="Estado civil" value={labelDe(ESTADO_CIVIL_OPTIONS, emp.estado_civil)} />
        <DetalleItem label="Cantidad de hijos" value={String(emp.cantidad_hijos ?? 0)} />
        <DetalleItem label="Fecha de nacimiento" value={fmtFechaCalendario(emp.fecha_nacimiento)} />
      </DetalleGrupo>

      <DetalleGrupo icon="lucide:building-2" titulo="ORGANIZACIÓN">
        <DetalleItem label="Sucursal" value={emp.sucursal?.descripcion} />
        <DetalleItem
          label="Centro de costo"
          value={emp.centro_costo ? `${emp.centro_costo.codigo} — ${emp.centro_costo.descripcion}` : null}
        />
        <DetalleItem
          label="Tipo de empleado"
          value={emp.tipo_empleado ? `${emp.tipo_empleado.codigo} — ${emp.tipo_empleado.nombre}` : null}
        />
      </DetalleGrupo>

      <DetalleGrupo icon="lucide:briefcase" titulo="LABORAL">
        <DetalleItem label="Fecha de ingreso" value={fmtFechaCalendario(emp.fecha_ingreso)} />
        <DetalleItem label="Fecha de egreso" value={emp.fecha_egreso ? fmtFechaCalendario(emp.fecha_egreso) : null} />
        <DetalleItem label="Salario base" value={`G. ${salario}`} />
        <DetalleItem label="Tipo de salario" value={labelDe(TIPO_SALARIO_OPTIONS, emp.tipo_salario)} />
      </DetalleGrupo>

      <DetalleGrupo icon="lucide:landmark" titulo="IPS Y BANCO">
        <DetalleItem label="Régimen IPS" value={labelDe(REGIMEN_IPS_OPTIONS, emp.regimen_ips)} />
        <DetalleItem label="N° IPS" value={emp.numero_ips} />
        <DetalleItem label="Banco" value={emp.banco?.descripcion} />
        <DetalleItem
          label="Cuenta bancaria"
          value={
            emp.cuenta_bancaria
              ? `${emp.cuenta_bancaria}${emp.tipo_cuenta ? ` (${labelDe(TIPO_CUENTA_OPTIONS, emp.tipo_cuenta)})` : ""}`
              : null
          }
        />
      </DetalleGrupo>

      {emp.observaciones && (
        <DetalleGrupo icon="lucide:sticky-note" titulo="OBSERVACIONES">
          <DetalleItem label="" value={emp.observaciones} />
        </DetalleGrupo>
      )}
    </Box>
  );
}

export function EmpleadosTab() {
  const { reloadPrereqs } = useRRHHContext();
  const { confirm, dialogs } = useConfirmDialog();
  const [, setSearchParams] = useSearchParams();

  const irAlLegajo = (empleadoId) => {
    setSearchParams(
      { tab: "legajos", subtab: "funcionario", empleadoId },
      { replace: false },
    );
  };

  const [data, setData] = useState([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(20);
  const [search, setSearch] = useState("");
  const [estadoFiltro, setEstadoFiltro] = useState("");
  const [tipoFiltro, setTipoFiltro] = useState("");
  const [loading, setLoading] = useState(false);
  const [expandedId, setExpandedId] = useState(null);

  const [showForm, setShowForm] = useState(false);


  const [editingId, setEditingId] = useState(null);
  const [form, setForm] = useState(EMPTY_FORM);
  const [saving, setSaving] = useState(false);
  const [validationMessages, setValidationMessages] = useState([]);

  const [cargos, setCargos] = useState([]);
  const [departamentos, setDepartamentos] = useState([]);
  const [tipos, setTipos] = useState([]);
  const [centrosCosto, setCentrosCosto] = useState([]);
  const [sucursales, setSucursales] = useState([]);
  const [bancos, setBancos] = useState([]);

  const totalPages = useMemo(() => Math.max(1, Math.ceil(total / limit)), [total, limit]);

  const cargarCatalogos = async () => {
    try {
      const [cargosResp, depsResp, tiposResp, ccResp, sucResp, bancosResp] = await Promise.all([
        getCargos(),
        getDepartamentos(),
        getTiposEmpleado(),
        getCentrosCosto(),
        getSucursales(1, 100),
        getBancosRrhh(),
      ]);
      setCargos(cargosResp || []);
      setDepartamentos(depsResp || []);
      setTipos(tiposResp || []);
      setCentrosCosto(ccResp || []);
      setSucursales(sucResp?.data || sucResp || []);
      setBancos(bancosResp || []);
    } catch (error) {
      console.error(error);
      toast.error("No se pudieron cargar los catálogos de RRHH");
    }
  };

  const load = async () => {
    try {
      setLoading(true);
      const resp = await getEmpleados({
        page,
        limit,
        search: search || undefined,
        estado: estadoFiltro || undefined,
        tipo_empleado_id: tipoFiltro || undefined,
      });
      setData(resp?.data || []);
      setTotal(resp?.total || 0);
    } catch (error) {
      console.error(error);
      toast.error("No se pudieron cargar empleados");
    } finally {
      setLoading(false);
    }
  };

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

  useEffect(() => {
    load();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [page, limit, estadoFiltro, tipoFiltro]);

  const handleNuevo = () => {
    setEditingId(null);
    setForm(EMPTY_FORM);
    setValidationMessages([]);
    setShowForm(true);
  };

  const handleEditar = (empleado) => {
    setEditingId(empleado.id);
    setForm({
      numero_empleado: empleado.numero_empleado || "",
      nombres: empleado.nombres || "",
      apellidos: empleado.apellidos || "",
      cedula_identidad: empleado.cedula_identidad || "",
      ruc: empleado.ruc || "",
      fecha_nacimiento: empleado.fecha_nacimiento ? empleado.fecha_nacimiento.slice(0, 10) : "",
      sexo: empleado.sexo || "M",
      estado_civil: empleado.estado_civil || "SOLTERO",
      cantidad_hijos: empleado.cantidad_hijos ?? 0,
      email: empleado.email || "",
      telefono: empleado.telefono || "",
      direccion: empleado.direccion || "",
      sucursal_id: empleado.sucursal_id || "",
      departamento_id: empleado.departamento_id || "",
      cargo_id: empleado.cargo_id || "",
      centro_costo_id: empleado.centro_costo_id || "",
      tipo_empleado_id: empleado.tipo_empleado_id || "",
      fecha_ingreso: empleado.fecha_ingreso ? empleado.fecha_ingreso.slice(0, 10) : "",
      fecha_egreso: empleado.fecha_egreso ? empleado.fecha_egreso.slice(0, 10) : "",
      salario_base: Number(empleado.salario_base) || 0,
      tipo_salario: empleado.tipo_salario || "MENSUAL",
      banco_id: empleado.banco_id || "",
      cuenta_bancaria: empleado.cuenta_bancaria || "",
      tipo_cuenta: empleado.tipo_cuenta || "",
      numero_ips: empleado.numero_ips || "",
      regimen_ips: empleado.regimen_ips || "GENERAL",
      observaciones: empleado.observaciones || "",
    });
    setValidationMessages([]);
    setShowForm(true);
  };

  const validar = () => {
    const errs = [];
    if (!form.nombres.trim()) errs.push({ campo: "Nombres", mensaje: "es obligatorio", anchorId: "emp-nombres" });
    if (!form.apellidos.trim()) errs.push({ campo: "Apellidos", mensaje: "es obligatorio", anchorId: "emp-apellidos" });
    if (!form.cedula_identidad.trim()) errs.push({ campo: "Cédula", mensaje: "es obligatoria", anchorId: "emp-ci" });
    if (!form.fecha_nacimiento) errs.push({ campo: "Fecha de nacimiento", mensaje: "es obligatoria", anchorId: "emp-fnac" });
    if (!form.fecha_ingreso) errs.push({ campo: "Fecha de ingreso", mensaje: "es obligatoria", anchorId: "emp-fingreso" });
    if (!form.sucursal_id) errs.push({ campo: "Sucursal", mensaje: "es obligatoria" });
    if (!form.departamento_id) errs.push({ campo: "Departamento", mensaje: "es obligatorio" });
    if (!form.cargo_id) errs.push({ campo: "Cargo", mensaje: "es obligatorio" });
    if (!form.centro_costo_id) errs.push({ campo: "Centro de costo", mensaje: "es obligatorio" });
    if (!form.tipo_empleado_id) errs.push({ campo: "Tipo de empleado", mensaje: "es obligatorio" });
    if (!Number(form.salario_base) || Number(form.salario_base) < 0)
      errs.push({ campo: "Salario base", mensaje: "debe ser mayor a 0", anchorId: "emp-salario" });
    return errs;
  };

  const handleGuardar = async () => {
    const errs = validar();
    if (errs.length) {
      setValidationMessages(errs);
      return;
    }
    try {
      setSaving(true);
      const payload = {
        ...form,
        salario_base: Number(form.salario_base),
        cantidad_hijos: Number(form.cantidad_hijos) || 0,
        ruc: form.ruc || undefined,
        email: form.email || undefined,
        telefono: form.telefono || undefined,
        direccion: form.direccion || undefined,
        banco_id: form.banco_id || undefined,
        cuenta_bancaria: form.cuenta_bancaria || undefined,
        tipo_cuenta: form.tipo_cuenta || undefined,
        numero_ips: form.numero_ips || undefined,
        observaciones: form.observaciones || undefined,
        fecha_egreso: form.fecha_egreso || undefined,
        // En alta dejamos que el backend autogenere el siguiente secuencial.
        // En edición no se permite cambiarlo manualmente desde este form.
        numero_empleado: undefined,
      };

      if (editingId) {
        await actualizarEmpleado(editingId, payload);
        toast.success("Empleado actualizado");
      } else {
        await crearEmpleado(payload);
        toast.success("Empleado creado");
      }
      setShowForm(false);
      setEditingId(null);
      setForm(EMPTY_FORM);
      load();
      reloadPrereqs();
    } catch (error) {
      const msg = error?.response?.data?.message;
      const detalle = Array.isArray(msg) ? msg.join(", ") : msg || "Error al guardar empleado";
      toast.error(detalle);
    } finally {
      setSaving(false);
    }
  };

  const handleEliminar = async (empleado) => {
    const ok = await confirm({
      title: "Dar de baja empleado",
      message: `¿Dar de baja a ${empleado.nombres} ${empleado.apellidos}? El empleado pasará a estado EGRESADO.`,
      confirmText: "Dar de baja",
      confirmColor: "error",
    });
    if (!ok) return;
    try {
      await eliminarEmpleado(empleado.id);
      toast.success("Empleado dado de baja");
      load();
      reloadPrereqs();
    } catch (error) {
      const msg = error?.response?.data?.message || "Error al dar de baja";
      toast.error(msg);
    }
  };

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

  if (showForm) {
    return (
      <Container>
        <FormPanel>
          <FormHead>
            <SectionTitle>
              <Icon icon={editingId ? "lucide:user-cog" : "lucide:user-plus"} />
              {editingId ? "Editar empleado" : "Nuevo empleado"}
            </SectionTitle>
            <GhostButton onClick={() => { setShowForm(false); setEditingId(null); setForm(EMPTY_FORM); }}>
              <Icon icon="lucide:x" /> Cerrar
            </GhostButton>
          </FormHead>

          <SectionTitle>
            <Icon icon="lucide:id-card" />
            Datos personales
          </SectionTitle>

          <FieldsGrid $cols={4}>
            {editingId && (
              <Field>
                <label>N° empleado</label>
                <input value={form.numero_empleado} readOnly disabled />
              </Field>
            )}
            <Field>
              <label>Cédula *</label>
              <input id="emp-ci" value={form.cedula_identidad}
                onChange={(e) => updateField("cedula_identidad", e.target.value)}
                placeholder="Ej: 2798309" />
              <Typography variant="caption" color="text.disabled">Sin puntos ni guiones — solo números</Typography>
            </Field>
            <Field>
              <label>RUC</label>
              <input value={form.ruc}
                onChange={(e) => updateField("ruc", e.target.value)}
                placeholder="Ej: 2798309-5" />
              <Typography variant="caption" color="text.disabled">Número sin puntos + dígito verificador</Typography>
            </Field>
            <Field>
              <label>N° IPS</label>
              <input value={form.numero_ips}
                onChange={(e) => updateField("numero_ips", e.target.value)}
                placeholder="Ej: 1234567" />
              <Typography variant="caption" color="text.disabled">N° de afiliado IPS del empleado</Typography>
            </Field>

            <Field $span={2}>
              <label>Nombres *</label>
              <input id="emp-nombres" value={form.nombres}
                onChange={(e) => updateField("nombres", e.target.value)}
                placeholder="Ej: Juan Carlos" />
            </Field>
            <Field $span={2}>
              <label>Apellidos *</label>
              <input id="emp-apellidos" value={form.apellidos}
                onChange={(e) => updateField("apellidos", e.target.value)}
                placeholder="Ej: González Pérez" />
            </Field>

            <Field>
              <label>Fecha nacimiento *</label>
              <input id="emp-fnac" type="date" value={form.fecha_nacimiento}
                onChange={(e) => updateField("fecha_nacimiento", e.target.value)} />
              <Typography variant="caption" color="text.disabled">Formato AAAA-MM-DD — se usa para calcular edad</Typography>
            </Field>
            <Field>
              <label>Sexo *</label>
              <SearchableSelect options={SEXO_OPTIONS} value={form.sexo}
                onChange={(id) => updateField("sexo", id || "M")} clearable={false} />
            </Field>
            <Field>
              <label>Estado civil *</label>
              <SearchableSelect options={ESTADO_CIVIL_OPTIONS} value={form.estado_civil}
                onChange={(id) => updateField("estado_civil", id || "SOLTERO")} clearable={false} />
            </Field>
            <Field>
              <label>Cantidad de hijos</label>
              <input type="number" min="0" value={form.cantidad_hijos}
                onChange={(e) => updateField("cantidad_hijos", e.target.value)} />
            </Field>

            <Field $span={2}>
              <label>Email</label>
              <input type="email" value={form.email}
                onChange={(e) => updateField("email", e.target.value)} />
            </Field>
            <Field>
              <label>Teléfono</label>
              <input value={form.telefono}
                onChange={(e) => updateField("telefono", e.target.value)} />
            </Field>
            <Field>
              <label>Dirección</label>
              <input value={form.direccion}
                onChange={(e) => updateField("direccion", e.target.value)} />
            </Field>
          </FieldsGrid>

          <Divider />

          <SectionTitle>
            <Icon icon="lucide:building-2" />
            Asignación organizacional
          </SectionTitle>

          <FieldsGrid $cols={4}>
            <Field>
              <label>Sucursal *</label>
              <SearchableSelect options={sucursales} value={form.sucursal_id}
                onChange={(id) => updateField("sucursal_id", id || "")}
                getOptionLabel={sucursalLabel}
                placeholder="Buscar sucursal..." />
            </Field>
            <Field>
              <label>Departamento *</label>
              <SearchableSelect options={departamentos} value={form.departamento_id}
                onChange={(id) => updateField("departamento_id", id || "")}
                getOptionLabel={departamentoLabel}
                placeholder="Buscar departamento..." />
            </Field>
            <Field>
              <label>Cargo *</label>
              <SearchableSelect options={cargos} value={form.cargo_id}
                onChange={(id) => updateField("cargo_id", id || "")}
                getOptionLabel={cargoLabel}
                placeholder="Buscar cargo..." />
            </Field>
            <Field>
              <label>Centro de costo *</label>
              <SearchableSelect options={centrosCosto} value={form.centro_costo_id}
                onChange={(id) => updateField("centro_costo_id", id || "")}
                getOptionLabel={ccLabel}
                placeholder="Buscar centro de costo..." />
            </Field>
            <Field $span={2}>
              <label>Tipo de empleado *</label>
              <SearchableSelect options={tipos} value={form.tipo_empleado_id}
                onChange={(id) => updateField("tipo_empleado_id", id || "")}
                getOptionLabel={tipoEmpleadoLabel}
                placeholder="Buscar tipo..." />
            </Field>
          </FieldsGrid>

          <Divider />

          <SectionTitle>
            <Icon icon="lucide:briefcase" />
            Datos laborales
          </SectionTitle>

          <FieldsGrid $cols={4}>
            <Field>
              <label>Fecha de ingreso *</label>
              <input id="emp-fingreso" type="date" value={form.fecha_ingreso}
                onChange={(e) => updateField("fecha_ingreso", e.target.value)} />
              <Typography variant="caption" color="text.disabled">Define antigüedad y cálculo de vacaciones</Typography>
            </Field>
            <Field>
              <label>Fecha de egreso</label>
              <input type="date" value={form.fecha_egreso}
                onChange={(e) => updateField("fecha_egreso", e.target.value)} />
              <Typography variant="caption" color="text.disabled">Solo completar si el empleado ya egresó</Typography>
            </Field>
            <MonedaInput
              id="emp-salario"
              label="Salario base *"
              fullWidth
              value={form.salario_base}
              onChange={(v) => updateField("salario_base", v)}
              helperText="Mínimo SMLV 2026: G. 2.550.307"
            />
            <Field>
              <label>Tipo de salario *</label>
              <SearchableSelect options={TIPO_SALARIO_OPTIONS} value={form.tipo_salario}
                onChange={(id) => updateField("tipo_salario", id || "MENSUAL")} clearable={false} />
            </Field>

            <Field>
              <label>Régimen IPS</label>
              <SearchableSelect options={REGIMEN_IPS_OPTIONS} value={form.regimen_ips}
                onChange={(id) => updateField("regimen_ips", id || "GENERAL")} clearable={false} />
              <Typography variant="caption" color="text.disabled">
                Define si el empleado aporta IPS. «Exento» no genera aportes en la liquidación.
              </Typography>
            </Field>
            <Field>
              <label>Banco</label>
              <SearchableSelect
                options={bancos.map((b) => ({ id: b.id, label: `${b.codigo ? b.codigo + " — " : ""}${b.descripcion}` }))}
                value={form.banco_id}
                onChange={(id) => updateField("banco_id", id || "")}
                placeholder="Elegí el banco…" />
              <Typography variant="caption" color="text.disabled">Banco donde el empleado cobra el sueldo</Typography>
            </Field>
            <Field>
              <label>Cuenta bancaria</label>
              <input value={form.cuenta_bancaria}
                onChange={(e) => updateField("cuenta_bancaria", e.target.value)}
                placeholder="Ej: 0011234567890" />
              <Typography variant="caption" color="text.disabled">Requerida para acreditaciones de sueldos</Typography>
            </Field>
            <Field>
              <label>Tipo de cuenta</label>
              <SearchableSelect options={TIPO_CUENTA_OPTIONS} value={form.tipo_cuenta}
                onChange={(id) => updateField("tipo_cuenta", id || "")}
                placeholder="Elegí el tipo…" />
            </Field>

            <Field $span={4}>
              <label>Observaciones</label>
              <textarea value={form.observaciones}
                onChange={(e) => updateField("observaciones", e.target.value)} />
            </Field>
          </FieldsGrid>

          <InlineValidationBanner
            errores={validationMessages}
            titulo="No se pudo guardar el empleado — revisá los siguientes campos:"
          />

          <Footer>
            <FooterActionButton type="button" $variant="danger" disabled={saving}
              onClick={() => { setShowForm(false); setEditingId(null); setForm(EMPTY_FORM); }}>
              <Icon icon="lucide:x-circle" /> Cancelar
            </FooterActionButton>
            <FooterActionButton type="button" $variant="primary" disabled={saving}
              onClick={handleGuardar}>
              <Icon icon="lucide:check-circle" />
              {saving ? "Guardando..." : editingId ? "Actualizar empleado" : "Crear empleado"}
            </FooterActionButton>
          </Footer>
        </FormPanel>
        {dialogs}
      </Container>
    );
  }

  return (
    <Container>
      <RRHHGuia seccion="empleados" />
      <RRHHPrereqChecklist tabKey="empleados" />
      <ListPanel>
        <ListBody>
          <ToolBar>
            <TextField
              size="small"
              placeholder="Buscar por nombre, número, cédula..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              onKeyDown={(e) => { if (e.key === "Enter") { setPage(1); load(); } }}
              className="grow"
              InputProps={{
                startAdornment: <InputAdornment position="start"><Icon icon="lucide:search" width={16} /></InputAdornment>,
                endAdornment: search && (
                  <InputAdornment position="end">
                    <IconButton size="small" onClick={() => { setSearch(""); setPage(1); load(); }}>
                      <Icon icon="lucide:x" width={16} />
                    </IconButton>
                  </InputAdornment>
                ),
              }}
            />
            <Box sx={{ minWidth: 200 }}>
              <SearchableSelect
                label="Estado"
                options={ESTADO_FILTRO_OPTIONS}
                value={estadoFiltro}
                onChange={(id) => { setEstadoFiltro(id || ""); setPage(1); }}
                placeholder="Todos los estados"
              />
            </Box>
            <Box sx={{ minWidth: 200 }}>
              <SearchableSelect
                label="Tipo de empleado"
                options={tipos}
                getOptionLabel={tipoEmpleadoLabel}
                value={tipoFiltro}
                onChange={(id) => { setTipoFiltro(id || ""); setPage(1); }}
                placeholder="Todos los tipos"
              />
            </Box>
            <Tooltip title="Refrescar">
              <GhostButton onClick={load} disabled={loading}>
                <Icon icon="lucide:refresh-cw" />
              </GhostButton>
            </Tooltip>
            <Box sx={{ flex: 1 }} />
            <FooterActionButton type="button" $variant="primary" onClick={handleNuevo}>
              <Icon icon="lucide:plus" /> Nuevo empleado
            </FooterActionButton>
          </ToolBar>

          {loading ? (
            <EmptyState>
              <Skeleton variant="rectangular" height={32} sx={{ mb: 1 }} />
              <Skeleton variant="rectangular" height={32} sx={{ mb: 1 }} />
              <Skeleton variant="rectangular" height={32} />
            </EmptyState>
          ) : data.length === 0 ? (
            <EmptyState>
              <Icon icon="lucide:users" width={36} />
              <Typography variant="body1" sx={{ mt: 1 }}>Sin empleados registrados</Typography>
              <Typography variant="body2" sx={{ opacity: 0.7 }}>
                Hacé click en «Nuevo empleado» para empezar.
              </Typography>
            </EmptyState>
          ) : (
            <TableWrap>
              <table>
                <thead>
                  <tr>
                    <th style={{ width: 36 }} />
                    <th>N°</th>
                    <th>Nombre</th>
                    <th>Cédula</th>
                    <th>Cargo</th>
                    <th>Departamento</th>
                    <th>Tipo</th>
                    <th style={{ textAlign: "right" }}>Salario base</th>
                    <th>Estado</th>
                    <th style={{ textAlign: "center" }}>Acciones</th>
                  </tr>
                </thead>
                <tbody>
                  {data.map((emp) => {
                    const expanded = expandedId === emp.id;
                    return (
                      <Fragment key={emp.id}>
                        <tr>
                          <td style={{ textAlign: "center" }}>
                            <Tooltip title={expanded ? "Ocultar detalles" : "Ver detalles"}>
                              <IconButton
                                size="small"
                                onClick={() => setExpandedId(expanded ? null : emp.id)}
                              >
                                <Icon
                                  icon={expanded ? "lucide:chevron-down" : "lucide:chevron-right"}
                                  width={16}
                                />
                              </IconButton>
                            </Tooltip>
                          </td>
                          <td>{emp.numero_empleado}</td>
                          <td>{emp.apellidos}, {emp.nombres}</td>
                          <td>{emp.cedula_identidad}</td>
                          <td>{emp.cargo?.nombre || "-"}</td>
                          <td>{emp.departamento?.nombre || "-"}</td>
                          <td>
                            {emp.tipo_empleado?.nombre
                              ? <Badge>{emp.tipo_empleado.nombre}</Badge>
                              : "-"}
                          </td>
                          <td style={{ textAlign: "right" }}>
                            {Number(emp.salario_base || 0).toLocaleString("es-PY")}
                          </td>
                          <td><Badge $state={emp.estado}>{emp.estado}</Badge></td>
                          <td style={{ textAlign: "center" }}>
                            <RowActions>
                              <Tooltip title="Ver legajo">
                                <IconButton size="small" color="secondary" onClick={() => irAlLegajo(emp.id)}>
                                  <Icon icon="lucide:folder-archive" width={16} />
                                </IconButton>
                              </Tooltip>
                              <Tooltip title="Editar">
                                <IconButton size="small" onClick={() => handleEditar(emp)}>
                                  <Icon icon="lucide:pencil" width={16} />
                                </IconButton>
                              </Tooltip>
                              <Tooltip title="Dar de baja">
                                <IconButton size="small" color="error" onClick={() => handleEliminar(emp)}>
                                  <Icon icon="lucide:user-minus" width={16} />
                                </IconButton>
                              </Tooltip>
                            </RowActions>
                          </td>
                        </tr>
                        {expanded && (
                          <tr>
                            <td colSpan={10} style={{ background: "rgba(125,125,125,0.06)", padding: 0 }}>
                              <EmpleadoDetalle emp={emp} />
                            </td>
                          </tr>
                        )}
                      </Fragment>
                    );
                  })}
                </tbody>
              </table>
            </TableWrap>
          )}

          <TablePaginationBar
            page={page}
            totalPages={totalPages}
            onPageChange={setPage}
            total={total}
            shown={data.length}
            noun="empleados"
            rowsPerPage={limit}
            onRowsPerPageChange={(n) => {
              setLimit(n);
              setPage(1);
            }}
          />
        </ListBody>
      </ListPanel>
      {dialogs}
    </Container>
  );
}
