import { Icon } from "@iconify/react";
import {
  Box,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  IconButton,
  Tooltip,
  Typography,
} from "@mui/material";
import { useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import {
  cambiarEstadoPrestamo,
  crearPrestamo,
  eliminarPrestamo,
  getCuotasPrestamo,
  getEmpleados,
  getPrestamos,
} from "../../api/rrhh.service";
import {
  Badge,
  Container,
  EmptyState,
  Field,
  FieldsGrid,
  Footer,
  FooterActionButton,
  FormHead,
  FormPanel,
  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 { RRHHPrereqChecklist } from "./_shared/RRHHPrereqChecklist";
import { RRHHEmptyState } from "./_shared/RRHHEmptyState";
import { useRRHHContext } from "./_shared/RRHHContext";
import { MonedaInput } from "../common/MonedaInput";
import { InlineValidationBanner } from "./_shared/InlineValidationBanner";
import { hoyISO } from "../../utils/fecha";

const empleadoOptionLabel = (e) => `${e.numero_empleado} — ${e.apellidos}, ${e.nombres}`;
const ESTADO_OPTIONS = [
  { id: "ACTIVO", label: "Activo" },
  { id: "SUSPENDIDO", label: "Suspendido" },
  { id: "CANCELADO", label: "Cancelado" },
];
const TIPO_DESCUENTO_OPTIONS = [
  { id: "MENSUAL", label: "Mensual" },
  { id: "QUINCENAL", label: "Quincenal" },
];

const todayYmd = () => hoyISO();

const buildEmptyForm = () => ({
  empleado_id: "",
  fecha_otorgamiento: todayYmd(),
  monto_total: 0,
  cantidad_cuotas: 6,
  tipo_descuento: "MENSUAL",
  primer_descuento_en: todayYmd(),
  observacion: "",
});

const fmtMonto = (value) => Number(value || 0).toLocaleString("es-PY");
const fmtFecha = (value) => {
  if (!value) return "-";
  const d = new Date(value);
  if (Number.isNaN(d.getTime())) return "-";
  return d.toLocaleDateString("es-PY");
};
const fmtPeriodo = (anio, mes, tipo) => {
  const base = `${String(mes).padStart(2, "0")}/${anio}`;
  if (tipo === "QUINCENAL_1") return `${base} · 1ª quincena`;
  if (tipo === "QUINCENAL_2") return `${base} · 2ª quincena`;
  return base;
};

export function PrestamosTab() {
  const { confirm, prompt, dialogs } = useConfirmDialog();
  const { reloadBadges } = useRRHHContext();
  const [data, setData] = useState([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(20);
  const [estadoFiltro, setEstadoFiltro] = useState("");
  const [empleadoFiltro, setEmpleadoFiltro] = useState("");
  const [loading, setLoading] = useState(false);

  const [empleados, setEmpleados] = useState([]);

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


  const [form, setForm] = useState(buildEmptyForm());
  const [saving, setSaving] = useState(false);
  const [erroresForm, setErroresForm] = useState([]);

  const [cuotasDialog, setCuotasDialog] = useState({ open: false, prestamo: null, cuotas: [], loading: false });

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

  const cargarEmpleados = async () => {
    try {
      const resp = await getEmpleados({ page: 1, limit: 200, estado: "ACTIVO" });
      setEmpleados(resp?.data || []);
    } catch {
      toast.error("No se pudieron cargar empleados");
    }
  };

  const load = async () => {
    try {
      setLoading(true);
      const params = { page, limit };
      if (estadoFiltro) params.estado = estadoFiltro;
      if (empleadoFiltro) params.empleado_id = empleadoFiltro;
      const resp = await getPrestamos(params);
      setData(resp?.data || []);
      setTotal(resp?.total || 0);
    } catch {
      toast.error("Error al cargar préstamos");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { cargarEmpleados(); }, []);
  useEffect(() => { load(); /* eslint-disable-next-line */ }, [page, limit, estadoFiltro, empleadoFiltro]);

  const montoCuotaPreview = useMemo(() => {
    const total = Number(form.monto_total) || 0;
    const cuotas = Number(form.cantidad_cuotas) || 0;
    if (!cuotas) return 0;
    return Math.round((total / cuotas) * 100) / 100;
  }, [form.monto_total, form.cantidad_cuotas]);

  const handleNuevo = () => {
    setForm(buildEmptyForm());
    setErroresForm([]);
    setShowForm(true);
  };

  const handleGuardar = async () => {
    const errs = [];
    if (!form.empleado_id) errs.push({ campo: "Empleado", mensaje: "Seleccioná un empleado" });
    if (!Number(form.monto_total) || Number(form.monto_total) <= 0) errs.push({ campo: "Monto total", mensaje: "Debe ser mayor a cero" });
    if (!Number(form.cantidad_cuotas) || Number(form.cantidad_cuotas) < 1) errs.push({ campo: "Cuotas", mensaje: "Debe ser al menos 1" });
    if (errs.length) { setErroresForm(errs); return; }
    setErroresForm([]);

    try {
      setSaving(true);
      await crearPrestamo({
        ...form,
        monto_total: Number(form.monto_total),
        cantidad_cuotas: Number(form.cantidad_cuotas),
        observacion: form.observacion || undefined,
      });
      toast.success("Préstamo creado con cronograma de cuotas");
      setShowForm(false);
      setForm(buildEmptyForm());
      load();
      reloadBadges();
    } catch (error) {
      toast.error(error?.response?.data?.message || "Error al crear préstamo");
    } finally {
      setSaving(false);
    }
  };

  const handleCambiarEstado = async (p, nuevoEstado, etiqueta) => {
    const colorByEstado = {
      ACTIVO: "success",
      SUSPENDIDO: "warning",
      CANCELADO: "error",
    };
    const comentario = await prompt({
      title: `${etiqueta} préstamo`,
      message: `El préstamo pasará a estado ${nuevoEstado}.`,
      label: "Comentario",
      placeholder: "Opcional",
      confirmText: etiqueta,
      confirmColor: colorByEstado[nuevoEstado] || "primary",
    });
    if (comentario === null) return;
    try {
      await cambiarEstadoPrestamo(p.id, { estado: nuevoEstado, comentario: comentario || undefined });
      toast.success(`Préstamo ${etiqueta.toLowerCase()}`);
      load();
      reloadBadges();
    } catch (error) {
      toast.error(error?.response?.data?.message || "No se pudo cambiar estado");
    }
  };

  const handleEliminar = async (p) => {
    const ok = await confirm({
      title: "Eliminar préstamo",
      message: "¿Eliminar este préstamo? No se puede deshacer.",
      confirmText: "Eliminar",
      confirmColor: "error",
    });
    if (!ok) return;
    try {
      await eliminarPrestamo(p.id);
      toast.success("Préstamo eliminado");
      load();
    } catch (error) {
      toast.error(error?.response?.data?.message || "No se pudo eliminar");
    }
  };

  const abrirCuotas = async (p) => {
    setCuotasDialog({ open: true, prestamo: p, cuotas: [], loading: true });
    try {
      const cuotas = await getCuotasPrestamo(p.id);
      setCuotasDialog({ open: true, prestamo: p, cuotas, loading: false });
    } catch {
      toast.error("Error al cargar cuotas");
      setCuotasDialog({ open: false, prestamo: null, cuotas: [], loading: false });
    }
  };

  const cerrarCuotas = () => setCuotasDialog({ open: false, prestamo: null, cuotas: [], loading: false });

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

  if (showForm) {
    return (
      <Container>
        <FormPanel>
          <FormHead>
            <SectionTitle>
              <Icon icon="lucide:hand-coins" /> Nuevo préstamo
            </SectionTitle>
            <GhostButton onClick={() => setShowForm(false)}>
              <Icon icon="lucide:x" /> Cerrar
            </GhostButton>
          </FormHead>

          <InlineValidationBanner errores={erroresForm} titulo="Revisá los siguientes campos" />

          <FieldsGrid $cols={4}>
            <Field $span={2}>
              <label>Empleado *</label>
              <SearchableSelect
                options={empleados}
                value={form.empleado_id}
                onChange={(id) => updateField("empleado_id", id || "")}
                getOptionLabel={empleadoOptionLabel}
                placeholder="Buscar por número, nombre o apellido..."
              />
            </Field>
            <Field>
              <label>Fecha otorgamiento *</label>
              <input type="date" value={form.fecha_otorgamiento}
                onChange={(e) => updateField("fecha_otorgamiento", e.target.value)} />
            </Field>
            <MonedaInput
              label="Monto total *"
              fullWidth
              value={form.monto_total}
              onChange={(v) => updateField("monto_total", v)}
              helperText="Monto bruto del préstamo — la cuota estimada se calcula abajo"
            />

            <Field>
              <label>Cantidad de cuotas *</label>
              <input type="number" min="1" max="120" step="1" value={form.cantidad_cuotas}
                onChange={(e) => updateField("cantidad_cuotas", e.target.value)} />
              <small style={{ opacity: 0.6, fontSize: "0.75rem" }}>Ej: 6 — máx. 120. La cuota estimada se calcula abajo automáticamente</small>
            </Field>
            <Field>
              <label>Tipo de descuento *</label>
              <SearchableSelect
                options={TIPO_DESCUENTO_OPTIONS}
                value={form.tipo_descuento}
                onChange={(id) => updateField("tipo_descuento", id || "MENSUAL")}
                clearable={false}
              />
            </Field>
            <Field>
              <label>Primer descuento *</label>
              <input type="date" value={form.primer_descuento_en}
                onChange={(e) => updateField("primer_descuento_en", e.target.value)} />
            </Field>
            <Field>
              <label>Cuota estimada</label>
              <input value={fmtMonto(montoCuotaPreview)} readOnly />
            </Field>

            <Field $span={4}>
              <label>Observación</label>
              <input value={form.observacion}
                onChange={(e) => updateField("observacion", e.target.value)} />
            </Field>
          </FieldsGrid>

          <Footer>
            <FooterActionButton type="button" $variant="danger" disabled={saving}
              onClick={() => setShowForm(false)}>
              <Icon icon="lucide:x-circle" /> Cancelar
            </FooterActionButton>
            <FooterActionButton type="button" $variant="primary" disabled={saving}
              onClick={handleGuardar}>
              <Icon icon="lucide:check-circle" />
              {saving ? "Guardando..." : "Otorgar préstamo"}
            </FooterActionButton>
          </Footer>
        </FormPanel>
        {dialogs}
      </Container>
    );
  }

  return (
    <Container>
      <RRHHGuia seccion="prestamos" />
      <RRHHPrereqChecklist tabKey="prestamos" />
      <ListPanel>
        <ListBody>
          <ToolBar>
            <Box sx={{ minWidth: 200 }}>
              <SearchableSelect
                label="Estado"
                options={ESTADO_OPTIONS}
                value={estadoFiltro}
                onChange={(id) => { setEstadoFiltro(id || ""); setPage(1); }}
                placeholder="Todos los estados"
              />
            </Box>
            <Box sx={{ minWidth: 280 }}>
              <SearchableSelect
                label="Empleado"
                options={empleados}
                value={empleadoFiltro}
                onChange={(id) => { setEmpleadoFiltro(id || ""); setPage(1); }}
                getOptionLabel={empleadoOptionLabel}
                placeholder="Todos los empleados"
              />
            </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 préstamo
            </FooterActionButton>
          </ToolBar>

          {loading ? (
            <EmptyState>Cargando...</EmptyState>
          ) : data.length === 0 ? (
            <RRHHEmptyState
              icon="lucide:hand-coins"
              titulo="Sin préstamos registrados"
              descripcion="Los préstamos al personal se descuentan en cuotas mensuales de la nómina. El sistema calcula la cuota automáticamente y controla que el total de descuentos no supere el 30% del salario."
              ctaLabel="Registrar préstamo"
              onCta={handleNuevo}
              onVerGuia={() => document.getElementById("rrhh-guia-prestamos")?.scrollIntoView({ behavior: "smooth" })}
            />
          ) : (
            <TableWrap>
              <table>
                <thead>
                  <tr>
                    <th>Fecha</th>
                    <th>Empleado</th>
                    <th style={{ textAlign: "right" }}>Monto total</th>
                    <th style={{ textAlign: "right" }}>Cuota</th>
                    <th style={{ textAlign: "center" }}>Cuotas</th>
                    <th>Tipo</th>
                    <th style={{ textAlign: "right" }}>Saldo pendiente</th>
                    <th>Estado</th>
                    <th style={{ textAlign: "center" }}>Acciones</th>
                  </tr>
                </thead>
                <tbody>
                  {data.map((p) => {
                    const emp = p.empleado;
                    const isActivo = p.estado === "ACTIVO";
                    const isSuspendido = p.estado === "SUSPENDIDO";
                    return (
                      <tr key={p.id}>
                        <td>{fmtFecha(p.fecha_otorgamiento)}</td>
                        <td>
                          {emp ? (
                            <>
                              <strong>{emp.numero_empleado}</strong> — {emp.apellidos}, {emp.nombres}
                            </>
                          ) : "-"}
                        </td>
                        <td style={{ textAlign: "right", fontFamily: "monospace" }}>{fmtMonto(p.monto_total)}</td>
                        <td style={{ textAlign: "right", fontFamily: "monospace" }}>{fmtMonto(p.monto_cuota)}</td>
                        <td style={{ textAlign: "center" }}>{p.cantidad_cuotas}</td>
                        <td>{p.tipo_descuento}</td>
                        <td style={{ textAlign: "right", fontFamily: "monospace" }}>{fmtMonto(p.saldo_pendiente)}</td>
                        <td><Badge $state={p.estado}>{p.estado}</Badge></td>
                        <td style={{ textAlign: "center" }}>
                          <RowActions>
                            <Tooltip title="Ver cuotas">
                              <IconButton size="small" onClick={() => abrirCuotas(p)}>
                                <Icon icon="lucide:list-ordered" width={16} />
                              </IconButton>
                            </Tooltip>
                            {isActivo && (
                              <Tooltip title="Suspender">
                                <IconButton size="small" color="warning"
                                  onClick={() => handleCambiarEstado(p, "SUSPENDIDO", "Suspender")}>
                                  <Icon icon="lucide:pause-circle" width={16} />
                                </IconButton>
                              </Tooltip>
                            )}
                            {isSuspendido && (
                              <Tooltip title="Reactivar">
                                <IconButton size="small" color="success"
                                  onClick={() => handleCambiarEstado(p, "ACTIVO", "Reactivar")}>
                                  <Icon icon="lucide:play-circle" width={16} />
                                </IconButton>
                              </Tooltip>
                            )}
                            {(isActivo || isSuspendido) && (
                              <Tooltip title="Cancelar préstamo">
                                <IconButton size="small" color="error"
                                  onClick={() => handleCambiarEstado(p, "CANCELADO", "Cancelar")}>
                                  <Icon icon="lucide:ban" width={16} />
                                </IconButton>
                              </Tooltip>
                            )}
                            <Tooltip title="Eliminar">
                              <IconButton size="small" color="error" onClick={() => handleEliminar(p)}>
                                <Icon icon="lucide:trash-2" width={16} />
                              </IconButton>
                            </Tooltip>
                          </RowActions>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </TableWrap>
          )}

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

      <Dialog open={cuotasDialog.open} onClose={cerrarCuotas} maxWidth="md" fullWidth>
        <DialogTitle>
          Cronograma de cuotas
          {cuotasDialog.prestamo?.empleado && (
            <Typography variant="caption" sx={{ display: "block", opacity: 0.7 }}>
              {cuotasDialog.prestamo.empleado.apellidos}, {cuotasDialog.prestamo.empleado.nombres}
              {" · "}{cuotasDialog.prestamo.cantidad_cuotas} cuotas {cuotasDialog.prestamo.tipo_descuento.toLowerCase()}es
            </Typography>
          )}
        </DialogTitle>
        <DialogContent dividers>
          {cuotasDialog.loading ? (
            <Typography>Cargando cuotas...</Typography>
          ) : cuotasDialog.cuotas.length === 0 ? (
            <Typography color="text.secondary">Sin cuotas</Typography>
          ) : (
            <TableWrap>
              <table>
                <thead>
                  <tr>
                    <th style={{ textAlign: "center" }}>#</th>
                    <th>Período</th>
                    <th style={{ textAlign: "right" }}>Monto</th>
                    <th>Estado</th>
                    <th>Fecha descuento</th>
                  </tr>
                </thead>
                <tbody>
                  {cuotasDialog.cuotas.map((c) => (
                    <tr key={c.id}>
                      <td style={{ textAlign: "center" }}>{c.numero_cuota}</td>
                      <td>{fmtPeriodo(c.periodo_anio, c.periodo_mes, c.periodo_tipo)}</td>
                      <td style={{ textAlign: "right", fontFamily: "monospace" }}>{fmtMonto(c.monto)}</td>
                      <td><Badge $state={c.estado === "DESCONTADO" ? "ACTIVO" : c.estado === "REPROGRAMADO" ? "INACTIVO" : "PENDIENTE"}>{c.estado}</Badge></td>
                      <td>{fmtFecha(c.fecha_descuento)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </TableWrap>
          )}
        </DialogContent>
        <DialogActions>
          <GhostButton onClick={cerrarCuotas}>Cerrar</GhostButton>
        </DialogActions>
      </Dialog>
      {dialogs}
    </Container>
  );
}
