import { Icon } from "@iconify/react";
import {
  Alert,
  Box,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  IconButton,
  Tooltip,
  Typography,
} from "@mui/material";
import { useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import {
  anularPlanillaExterna,
  descargarPlantillaPlanillaExterna,
  getPlanillaExterna,
  getPlanillasExternas,
  importarPlanillaExterna,
} from "../../api/rrhh.service";
import { useConfirmDialog } from "../../hooks/useConfirmDialog";
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 { RRHHGuia } from "./_shared/RRHHGuia";
import { RRHHPrereqChecklist } from "./_shared/RRHHPrereqChecklist";
import { RRHHEmptyState } from "./_shared/RRHHEmptyState";

const ESTADO_OPTIONS = [
  { id: "IMPORTADA", label: "Importada" },
  { id: "APLICADA", label: "Aplicada" },
  { id: "ANULADA", label: "Anulada" },
];

const MES_OPTIONS = [
  { id: 1, label: "01 — Enero" }, { id: 2, label: "02 — Febrero" },
  { id: 3, label: "03 — Marzo" }, { id: 4, label: "04 — Abril" },
  { id: 5, label: "05 — Mayo" }, { id: 6, label: "06 — Junio" },
  { id: 7, label: "07 — Julio" }, { id: 8, label: "08 — Agosto" },
  { id: 9, label: "09 — Septiembre" }, { id: 10, label: "10 — Octubre" },
  { id: 11, label: "11 — Noviembre" }, { id: 12, label: "12 — Diciembre" },
];

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

export function PlanillasExternasTab() {
  const { confirm, prompt, dialogs } = useConfirmDialog();

  const [data, setData] = useState([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(20);
  const [estadoFiltro, setEstadoFiltro] = useState("");
  const [loading, setLoading] = useState(false);

  const [showImport, setShowImport] = useState(false);
  const [importing, setImporting] = useState(false);
  const [archivo, setArchivo] = useState(null);
  const [importForm, setImportForm] = useState(() => {
    const today = new Date();
    return {
      nombre: "",
      periodo_anio: today.getFullYear(),
      periodo_mes: today.getMonth() + 1,
    };
  });
  const [resultado, setResultado] = useState(null); // resultado de la última importación

  const [detalleDialog, setDetalleDialog] = useState({
    open: false,
    loading: false,
    planilla: null,
  });

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

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

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

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

  const handleArchivoChange = (e) => {
    const file = e.target.files?.[0] || null;
    setArchivo(file);
    if (file && !importForm.nombre.trim()) {
      const baseName = file.name.replace(/\.(xlsx|xls|csv)$/i, "");
      updateImport("nombre", baseName);
    }
  };

  const handleDescargarPlantilla = async () => {
    try {
      const blob = await descargarPlantillaPlanillaExterna();
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = "planilla_externa_rrhh.xlsx";
      document.body.appendChild(a);
      a.click();
      a.remove();
      URL.revokeObjectURL(url);
    } catch {
      toast.error("No se pudo descargar la plantilla");
    }
  };

  const handleImportar = async () => {
    if (!archivo) return toast.error("Adjuntá un archivo .xlsx, .xls o .csv");
    if (!importForm.nombre.trim()) return toast.error("Indicá un nombre descriptivo");

    try {
      setImporting(true);
      setResultado(null);
      const resp = await importarPlanillaExterna({
        archivo,
        nombre: importForm.nombre.trim(),
        periodo_anio: importForm.periodo_anio,
        periodo_mes: importForm.periodo_mes,
      });
      setResultado(resp);
      const validos = resp.registros_validos || 0;
      const invalidos = resp.registros_invalidos || 0;
      if (invalidos === 0) {
        toast.success(`Planilla importada · ${validos} filas`);
      } else {
        toast.warning(`Importada con ${invalidos} errores · ${validos} filas válidas`);
      }
      load();
    } catch (error) {
      const msg = error?.response?.data?.message;
      toast.error(Array.isArray(msg) ? msg.join(", ") : msg || "Error al importar");
    } finally {
      setImporting(false);
    }
  };

  const handleNuevaImportacion = () => {
    setArchivo(null);
    setResultado(null);
    setImportForm({
      nombre: "",
      periodo_anio: new Date().getFullYear(),
      periodo_mes: new Date().getMonth() + 1,
    });
    setShowImport(true);
  };

  const handleVerDetalle = async (planilla) => {
    setDetalleDialog({ open: true, loading: true, planilla: null });
    try {
      const detalle = await getPlanillaExterna(planilla.id);
      setDetalleDialog({ open: true, loading: false, planilla: detalle });
    } catch {
      toast.error("No se pudo cargar el detalle");
      setDetalleDialog({ open: false, loading: false, planilla: null });
    }
  };

  const handleAnular = async (p) => {
    const comentario = await prompt({
      title: "Anular planilla",
      message: `Planilla "${p.nombre}" del período ${fmtPeriodo(p.periodo_anio, p.periodo_mes)}.`,
      label: "Comentario",
      placeholder: "Opcional",
      confirmText: "Anular",
      confirmColor: "warning",
    });
    if (comentario === null) return;
    try {
      await anularPlanillaExterna(p.id, comentario ? { comentario } : {});
      toast.success("Planilla anulada");
      load();
    } catch (error) {
      toast.error(error?.response?.data?.message || "No se pudo anular");
    }
  };

  if (showImport) {
    return (
      <Container>
        <FormPanel>
          <FormHead>
            <SectionTitle>
              <Icon icon="lucide:file-spreadsheet" /> Importar planilla externa
            </SectionTitle>
            <Box sx={{ display: "flex", gap: 0.5 }}>
              <GhostButton onClick={handleDescargarPlantilla}>
                <Icon icon="lucide:download" /> Descargar plantilla
              </GhostButton>
              <GhostButton onClick={() => setShowImport(false)}>
                <Icon icon="lucide:x" /> Cerrar
              </GhostButton>
            </Box>
          </FormHead>

          <Alert severity="info" sx={{ mb: 2 }}>
            Subí un archivo .xlsx, .xls o .csv. <strong>Columnas obligatorias:</strong> numero_empleado, codigo_concepto, tipo (INGRESO/EGRESO), monto. <strong>Opcional:</strong> observacion.
          </Alert>

          <FieldsGrid $cols={4}>
            <Field $span={2}>
              <label>Nombre descriptivo *</label>
              <input value={importForm.nombre}
                onChange={(e) => updateImport("nombre", e.target.value)}
                placeholder="Bonos noviembre 2026" />
            </Field>
            <Field>
              <label>Período año *</label>
              <input type="number" min="2020" max="2100" value={importForm.periodo_anio}
                onChange={(e) => updateImport("periodo_anio", Number(e.target.value))} />
            </Field>
            <Field>
              <label>Período mes *</label>
              <SearchableSelect options={MES_OPTIONS} value={importForm.periodo_mes}
                onChange={(id) => updateImport("periodo_mes", id ?? importForm.periodo_mes)}
                clearable={false} />
            </Field>

            <Field $span={4}>
              <label>Archivo (.xlsx, .xls, .csv) *</label>
              <input type="file" accept=".xlsx,.xls,.csv"
                onChange={handleArchivoChange}
                style={{ padding: 8 }} />
              {archivo && (
                <Typography variant="caption" sx={{ opacity: 0.7, mt: 0.5 }}>
                  {archivo.name} · {(archivo.size / 1024).toFixed(1)} KB
                </Typography>
              )}
            </Field>
          </FieldsGrid>

          {resultado && (
            <Alert
              severity={resultado.registros_invalidos > 0 ? "warning" : "success"}
              sx={{ mt: 2 }}
            >
              <Typography variant="body2" sx={{ fontWeight: 600 }}>
                Importada: {resultado.registros_validos} válidas · {resultado.registros_invalidos} con errores
              </Typography>
              <Typography variant="caption">
                Ingresos: {fmtMonto(resultado.total_ingresos)} · Egresos: {fmtMonto(resultado.total_egresos)}
              </Typography>
              {Array.isArray(resultado.errores) && resultado.errores.length > 0 && (
                <Box sx={{ mt: 1, maxHeight: 180, overflow: "auto", fontSize: "0.8rem" }}>
                  {resultado.errores.slice(0, 20).map((e, idx) => (
                    <div key={idx}>
                      Fila {e.fila}: {e.mensaje}
                    </div>
                  ))}
                  {resultado.errores.length > 20 && (
                    <div style={{ opacity: 0.7 }}>
                      ... y {resultado.errores.length - 20} más
                    </div>
                  )}
                </Box>
              )}
            </Alert>
          )}

          <Footer>
            <FooterActionButton type="button" $variant="danger" disabled={importing}
              onClick={() => setShowImport(false)}>
              <Icon icon="lucide:x-circle" /> Cerrar
            </FooterActionButton>
            <FooterActionButton type="button" $variant="primary" disabled={importing || !archivo}
              onClick={handleImportar}>
              <Icon icon="lucide:upload" />
              {importing ? "Importando..." : "Importar"}
            </FooterActionButton>
          </Footer>
        </FormPanel>
        {dialogs}
      </Container>
    );
  }

  return (
    <Container>
      <RRHHGuia seccion="planillas" />
      <RRHHPrereqChecklist tabKey="planillas" />
      <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>
            <Tooltip title="Refrescar">
              <GhostButton onClick={load} disabled={loading}>
                <Icon icon="lucide:refresh-cw" />
              </GhostButton>
            </Tooltip>
            <GhostButton onClick={handleDescargarPlantilla}>
              <Icon icon="lucide:download" /> Plantilla
            </GhostButton>
            <Box sx={{ flex: 1 }} />
            <FooterActionButton type="button" $variant="primary" onClick={handleNuevaImportacion}>
              <Icon icon="lucide:upload" /> Importar planilla
            </FooterActionButton>
          </ToolBar>

          {loading ? (
            <EmptyState>Cargando...</EmptyState>
          ) : data.length === 0 ? (
            <RRHHEmptyState
              icon="lucide:file-spreadsheet"
              titulo="Sin planillas importadas"
              descripcion="Las planillas externas permiten importar masivamente novedades desde un archivo Excel o CSV. Descargá la plantilla, completá los datos de tus empleados y subila acá."
              ctaLabel="Subir planilla"
              onCta={handleNuevaImportacion}
              guiaSeccion="planillas"
            />
          ) : (
            <TableWrap>
              <table>
                <thead>
                  <tr>
                    <th>Período</th>
                    <th>Nombre</th>
                    <th style={{ textAlign: "right" }}>Total filas</th>
                    <th style={{ textAlign: "right" }}>Válidas</th>
                    <th style={{ textAlign: "right" }}>Errores</th>
                    <th style={{ textAlign: "right" }}>Ingresos</th>
                    <th style={{ textAlign: "right" }}>Egresos</th>
                    <th>Estado</th>
                    <th>Importada</th>
                    <th style={{ textAlign: "center" }}>Acciones</th>
                  </tr>
                </thead>
                <tbody>
                  {data.map((p) => {
                    const puedeAnular = p.estado === "IMPORTADA";
                    return (
                      <tr key={p.id}>
                        <td>{fmtPeriodo(p.periodo_anio, p.periodo_mes)}</td>
                        <td>{p.nombre}</td>
                        <td style={{ textAlign: "right", fontFamily: "monospace" }}>{p.total_registros}</td>
                        <td style={{ textAlign: "right", fontFamily: "monospace" }}>{p.registros_validos}</td>
                        <td style={{ textAlign: "right", fontFamily: "monospace", color: p.registros_invalidos ? "#dc3545" : undefined }}>
                          {p.registros_invalidos}
                        </td>
                        <td style={{ textAlign: "right", fontFamily: "monospace" }}>{fmtMonto(p.total_ingresos)}</td>
                        <td style={{ textAlign: "right", fontFamily: "monospace" }}>{fmtMonto(p.total_egresos)}</td>
                        <td><Badge $state={p.estado}>{p.estado}</Badge></td>
                        <td>{fmtFecha(p.created_at)}</td>
                        <td style={{ textAlign: "center" }}>
                          <RowActions>
                            <Tooltip title="Ver detalle">
                              <IconButton size="small" onClick={() => handleVerDetalle(p)}>
                                <Icon icon="lucide:eye" width={16} />
                              </IconButton>
                            </Tooltip>
                            {puedeAnular && (
                              <Tooltip title="Anular">
                                <IconButton size="small" color="warning" onClick={() => handleAnular(p)}>
                                  <Icon icon="lucide:ban" width={16} />
                                </IconButton>
                              </Tooltip>
                            )}
                          </RowActions>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </TableWrap>
          )}

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

      <Dialog
        open={detalleDialog.open}
        onClose={() => setDetalleDialog({ open: false, loading: false, planilla: null })}
        maxWidth="lg"
        fullWidth
      >
        <DialogTitle>
          Detalle de planilla
          {detalleDialog.planilla && (
            <Typography variant="caption" sx={{ display: "block", opacity: 0.7 }}>
              {detalleDialog.planilla.nombre} · {fmtPeriodo(detalleDialog.planilla.periodo_anio, detalleDialog.planilla.periodo_mes)}
            </Typography>
          )}
        </DialogTitle>
        <DialogContent dividers>
          {detalleDialog.loading ? (
            <Typography>Cargando detalle...</Typography>
          ) : detalleDialog.planilla ? (
            <>
              <Box sx={{ display: "flex", gap: 2, mb: 2, flexWrap: "wrap" }}>
                <Box>
                  <Typography variant="caption" sx={{ opacity: 0.7 }}>Estado</Typography>
                  <div><Badge $state={detalleDialog.planilla.estado}>{detalleDialog.planilla.estado}</Badge></div>
                </Box>
                <Box>
                  <Typography variant="caption" sx={{ opacity: 0.7 }}>Filas válidas / total</Typography>
                  <Typography variant="body2">
                    {detalleDialog.planilla.registros_validos} / {detalleDialog.planilla.total_registros}
                  </Typography>
                </Box>
                <Box>
                  <Typography variant="caption" sx={{ opacity: 0.7 }}>Ingresos / Egresos</Typography>
                  <Typography variant="body2" sx={{ fontFamily: "monospace" }}>
                    {fmtMonto(detalleDialog.planilla.total_ingresos)} / {fmtMonto(detalleDialog.planilla.total_egresos)}
                  </Typography>
                </Box>
              </Box>

              <SectionTitle>
                <Icon icon="lucide:list" /> Filas válidas ({detalleDialog.planilla.detalles?.length || 0})
              </SectionTitle>
              {detalleDialog.planilla.detalles?.length === 0 ? (
                <EmptyState>Sin filas válidas</EmptyState>
              ) : (
                <TableWrap>
                  <table>
                    <thead>
                      <tr>
                        <th style={{ textAlign: "center" }}>Fila</th>
                        <th>Empleado</th>
                        <th>Concepto</th>
                        <th>Tipo</th>
                        <th style={{ textAlign: "right" }}>Monto</th>
                        <th>Observación</th>
                        <th style={{ textAlign: "center" }}>Aplicado</th>
                      </tr>
                    </thead>
                    <tbody>
                      {detalleDialog.planilla.detalles.map((d) => (
                        <tr key={d.id}>
                          <td style={{ textAlign: "center" }}>{d.fila_origen ?? "-"}</td>
                          <td>
                            {d.empleado
                              ? `${d.empleado.numero_empleado} — ${d.empleado.apellidos}, ${d.empleado.nombres}`
                              : "-"}
                          </td>
                          <td>{d.concepto ? `${d.concepto.codigo} — ${d.concepto.nombre}` : "-"}</td>
                          <td>
                            <Badge $state={d.tipo === "INGRESO" ? "ACTIVO" : "ANULADA"}>{d.tipo}</Badge>
                          </td>
                          <td style={{ textAlign: "right", fontFamily: "monospace" }}>{fmtMonto(d.monto)}</td>
                          <td>{d.observacion || "—"}</td>
                          <td style={{ textAlign: "center" }}>{d.aplicado ? "✓" : "—"}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </TableWrap>
              )}

              {Array.isArray(detalleDialog.planilla.errores_importacion) &&
                detalleDialog.planilla.errores_importacion.length > 0 && (
                <>
                  <SectionTitle>
                    <Icon icon="lucide:alert-triangle" /> Errores ({detalleDialog.planilla.errores_importacion.length})
                  </SectionTitle>
                  <TableWrap>
                    <table>
                      <thead>
                        <tr>
                          <th style={{ textAlign: "center" }}>Fila</th>
                          <th>Mensaje</th>
                          <th>Datos</th>
                        </tr>
                      </thead>
                      <tbody>
                        {detalleDialog.planilla.errores_importacion.map((e, idx) => (
                          <tr key={idx}>
                            <td style={{ textAlign: "center" }}>{e.fila}</td>
                            <td>{e.mensaje}</td>
                            <td style={{ fontFamily: "monospace", fontSize: "0.78rem", opacity: 0.8 }}>
                              {JSON.stringify(e.datos)}
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </TableWrap>
                </>
              )}
            </>
          ) : (
            <Typography color="text.secondary">Sin detalle</Typography>
          )}
        </DialogContent>
        <DialogActions>
          <GhostButton onClick={() => setDetalleDialog({ open: false, loading: false, planilla: null })}>
            Cerrar
          </GhostButton>
        </DialogActions>
      </Dialog>

      {dialogs}
    </Container>
  );
}
