import { Icon } from "@iconify/react";
import {
  Box,
  Button,
  Chip,
  CircularProgress,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Divider,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Typography,
} from "@mui/material";
import { useQuery } from "@tanstack/react-query";
import { useNavigate } from "react-router-dom";
import { listarRendiciones, listarCxpEmpleados } from "../../../api/rendicion-viaticos.service";
import { EmptyState } from "../../_standards";
import {
  ESTADO_RENDICION_LIST,
  getEstadoRendicion,
} from "../../_standards/enums/estadosRendicionViatico";
import { fmtMoneda } from "../../_standards/enums/monedas";
import { fmtFechaCalendario } from "../../../utils/fecha";

/**
 * Modal que muestra el detalle de saldos de un empleado:
 *   - Rendiciones abiertas (no CERRADA/ANULADA)
 *   - CxP pendientes (pendiente/parcial)
 *
 * Cada fila enlaza al detalle correspondiente.
 */
export function DetalleEmpleadoSaldoDialog({ open, onClose, empleado }) {
  const navigate = useNavigate();
  const empleadoId = empleado?.id;

  const estadosAbiertos = ESTADO_RENDICION_LIST
    ? ESTADO_RENDICION_LIST.map((e) => e.value).filter(
        (v) => !["CERRADA", "ANULADA"].includes(v),
      )
    : ["ADELANTO_PAGADO", "SIN_ADELANTO", "PENDIENTE_APROBACION", "BORRADOR", "RENDIDA"];

  const { data: rendicionesResp, isLoading: loadingRend } = useQuery({
    queryKey: ["rendiciones-empleado-drill", empleadoId],
    queryFn: () => listarRendiciones({ empleado_id: empleadoId, limit: 100 }),
    enabled: !!(open && empleadoId),
    staleTime: 30 * 1000,
  });
  const rendiciones = (rendicionesResp?.items ?? []).filter((r) =>
    estadosAbiertos.includes(r.estado),
  );

  const { data: cxpResp, isLoading: loadingCxp } = useQuery({
    queryKey: ["cxp-empleado-drill", empleadoId],
    queryFn: () => listarCxpEmpleados({ empleado_id: empleadoId }),
    enabled: !!(open && empleadoId),
    staleTime: 30 * 1000,
  });
  const cxps = Array.isArray(cxpResp) ? cxpResp : cxpResp?.items ?? [];

  const irARendicion = (id) => {
    onClose?.();
    navigate(`/rendicion-viaticos/${id}`);
  };
  const irACxp = () => {
    onClose?.();
    navigate(`/rendicion-viaticos/cxp-empleados?empleado_id=${empleadoId}`);
  };

  return (
    <Dialog open={open} onClose={onClose} maxWidth="lg" fullWidth>
      <DialogTitle sx={{ display: "flex", alignItems: "center", gap: 1 }}>
        <Icon icon="mdi:account-eye" />
        Detalle de saldos —{" "}
        {empleado ? (
          <Box component="span">
            <Typography component="span" fontWeight={700}>
              {empleado.nombres} {empleado.apellidos}
            </Typography>
            {empleado.numero_empleado && (
              <Typography component="span" variant="caption" sx={{ ml: 1, color: "text.secondary" }}>
                #{empleado.numero_empleado}
              </Typography>
            )}
          </Box>
        ) : (
          ""
        )}
      </DialogTitle>
      <DialogContent dividers>
        {/* Rendiciones abiertas */}
        <Stack direction="row" alignItems="center" spacing={1} sx={{ mb: 1 }}>
          <Icon icon="mdi:briefcase-account" />
          <Typography variant="subtitle2" fontWeight={700}>
            Rendiciones abiertas
          </Typography>
          <Chip size="small" label={rendiciones.length} />
        </Stack>
        {loadingRend ? (
          <Box sx={{ py: 3, display: "flex", justifyContent: "center" }}>
            <CircularProgress size={24} />
          </Box>
        ) : rendiciones.length === 0 ? (
          <Box sx={{ py: 2 }}>
            <EmptyState
              icon="mdi:briefcase-check-outline"
              title="Sin rendiciones abiertas"
              description="Este empleado no tiene rendiciones sin cerrar."
            />
          </Box>
        ) : (
          <TableContainer sx={{ mb: 2 }}>
            <Table size="small">
              <TableHead>
                <TableRow>
                  <TableCell sx={{ fontWeight: 600 }}>Número</TableCell>
                  <TableCell sx={{ fontWeight: 600 }}>Concepto</TableCell>
                  <TableCell sx={{ fontWeight: 600 }}>Inicio</TableCell>
                  <TableCell sx={{ fontWeight: 600 }} align="right">Adelantado</TableCell>
                  <TableCell sx={{ fontWeight: 600 }} align="right">Rendido</TableCell>
                  <TableCell sx={{ fontWeight: 600 }} align="right">Saldo</TableCell>
                  <TableCell sx={{ fontWeight: 600 }}>Estado</TableCell>
                  <TableCell sx={{ fontWeight: 600 }} align="center">Ir</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {rendiciones.map((r) => {
                  const info = getEstadoRendicion(r.estado);
                  const codigo = r.moneda?.codigo || "PYG";
                  return (
                    <TableRow key={r.id} hover>
                      <TableCell>
                        <Typography sx={{ fontFamily: "monospace", fontWeight: 600 }}>
                          {r.numero_rendicion}
                        </Typography>
                      </TableCell>
                      <TableCell>{r.concepto}</TableCell>
                      <TableCell>{fmtFechaCalendario(r.fecha_inicio)}</TableCell>
                      <TableCell align="right">
                        {fmtMoneda(Number(r.monto_adelanto_total || 0), codigo)}
                      </TableCell>
                      <TableCell align="right">
                        {fmtMoneda(Number(r.monto_rendido_total || 0), codigo)}
                      </TableCell>
                      <TableCell align="right">
                        <Typography
                          sx={{
                            fontWeight: 700,
                            color:
                              Number(r.saldo) > 0
                                ? "warning.main"
                                : Number(r.saldo) < 0
                                  ? "error.main"
                                  : "success.main",
                          }}
                        >
                          {fmtMoneda(Number(r.saldo || 0), codigo)}
                        </Typography>
                      </TableCell>
                      <TableCell>
                        <Chip size="small" label={info.label} color={info.color} variant="outlined" />
                      </TableCell>
                      <TableCell align="center">
                        <Button
                          size="small"
                          onClick={() => irARendicion(r.id)}
                          startIcon={<Icon icon="lucide:eye" width={14} />}
                        >
                          Ver
                        </Button>
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          </TableContainer>
        )}

        <Divider sx={{ my: 2 }} />

        {/* CxP pendientes */}
        <Stack direction="row" alignItems="center" spacing={1} sx={{ mb: 1 }}>
          <Icon icon="mdi:account-arrow-left" />
          <Typography variant="subtitle2" fontWeight={700}>
            CxP pendientes (reintegros diferidos)
          </Typography>
          <Chip size="small" label={cxps.length} />
        </Stack>
        {loadingCxp ? (
          <Box sx={{ py: 3, display: "flex", justifyContent: "center" }}>
            <CircularProgress size={24} />
          </Box>
        ) : cxps.length === 0 ? (
          <Box sx={{ py: 2 }}>
            <EmptyState
              icon="mdi:account-check-outline"
              title="Sin CxP pendientes"
              description="Este empleado no tiene reintegros diferidos por cobrar."
            />
          </Box>
        ) : (
          <TableContainer>
            <Table size="small">
              <TableHead>
                <TableRow>
                  <TableCell sx={{ fontWeight: 600 }}>Fecha</TableCell>
                  <TableCell sx={{ fontWeight: 600 }}>Origen</TableCell>
                  <TableCell sx={{ fontWeight: 600 }} align="right">Monto original</TableCell>
                  <TableCell sx={{ fontWeight: 600 }} align="right">Pagado</TableCell>
                  <TableCell sx={{ fontWeight: 600 }} align="right">Saldo</TableCell>
                  <TableCell sx={{ fontWeight: 600 }}>Estado</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {cxps.map((c) => {
                  const rend = c.devoluciones?.[0]?.rendicion;
                  return (
                    <TableRow key={c.id} hover>
                      <TableCell>{fmtFechaCalendario(c.fecha_generacion)}</TableCell>
                      <TableCell>
                        {rend ? (
                          <Box>
                            <Typography variant="body2" fontWeight={600}>
                              {rend.numero_rendicion}
                            </Typography>
                            <Typography variant="caption" color="text.secondary">
                              {rend.concepto}
                            </Typography>
                          </Box>
                        ) : (
                          c.origen_tipo
                        )}
                      </TableCell>
                      <TableCell align="right">
                        {fmtMoneda(Number(c.monto_original || 0), "PYG")}
                      </TableCell>
                      <TableCell align="right">
                        {fmtMoneda(Number(c.monto_pagado || 0), "PYG")}
                      </TableCell>
                      <TableCell align="right">
                        <Typography sx={{ fontWeight: 700, color: "warning.main" }}>
                          {fmtMoneda(Number(c.saldo_pendiente || 0), "PYG")}
                        </Typography>
                      </TableCell>
                      <TableCell>
                        <Chip size="small" label={c.estado} variant="outlined" />
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          </TableContainer>
        )}
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>Cerrar</Button>
        {cxps.length > 0 && (
          <Button variant="contained" onClick={irACxp} startIcon={<Icon icon="mdi:cash-check" />}>
            Ir a CxP a Empleados
          </Button>
        )}
      </DialogActions>
    </Dialog>
  );
}

export default DetalleEmpleadoSaldoDialog;
