import { useEffect, useMemo, useState } from "react";
import {
  Alert,
  Box,
  Button,
  Checkbox,
  Chip,
  CircularProgress,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  FormControlLabel,
  IconButton,
  Paper,
  Radio,
  RadioGroup,
  Stack,
  Step,
  StepLabel,
  Stepper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Typography,
} from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import dayjs from "dayjs";
import "dayjs/locale/es";
import { Icon } from "@iconify/react";
import { toast } from "sonner";
import {
  PrereqChecklist,
  ScreenGuia,
  InlineValidationBanner,
} from "../_standards";
import {
  COB_REFI_POLITICA,
  COB_REFI_POLITICA_META,
} from "../_standards/enums/estados";
import { fmtFechaCalendario, toFechaCalendarioISO } from "../../utils/fecha";
import { getCuotasPendientes } from "../../api/cobros.service";
import {
  simularRefinanciacion,
  createRefinanciacion,
} from "../../api/cobranzas.service";

const STEPS = [
  "Cuotas a refinanciar",
  "Política de intereses",
  "Nuevo plan",
  "Confirmación",
];

const fmtGs = (n) =>
  new Intl.NumberFormat("es-PY").format(Math.round(Number(n) || 0));

export function RefinanciacionWizard({ open, onClose, clienteId, onSuccess }) {
  const [step, setStep] = useState(0);

  const [cuotas, setCuotas] = useState([]);
  const [loadingCuotas, setLoadingCuotas] = useState(false);
  const [errorCuotas, setErrorCuotas] = useState(null);
  const [seleccion, setSeleccion] = useState({});
  // Se incrementa para volver a pedir las cuotas desde el botón "Reintentar".
  const [recargaCuotas, setRecargaCuotas] = useState(0);

  const [politica, setPolitica] = useState(COB_REFI_POLITICA.CAPITALIZAR);

  const [cantidadCuotas, setCantidadCuotas] = useState(6);
  const [tasaInteres, setTasaInteres] = useState(0);
  const [fechaPrimera, setFechaPrimera] = useState(dayjs().add(30, "day"));
  const [intervaloDias, setIntervaloDias] = useState(30);

  const [simulando, setSimulando] = useState(false);
  const [errorSim, setErrorSim] = useState(null);
  const [simulacion, setSimulacion] = useState(null);

  const [motivo, setMotivo] = useState("");
  const [documentoUrl, setDocumentoUrl] = useState("");
  const [guardando, setGuardando] = useState(false);
  const [errorSubmit, setErrorSubmit] = useState(null);

  // Reset al abrir
  useEffect(() => {
    if (!open) return;
    setStep(0);
    setSeleccion({});
    setPolitica(COB_REFI_POLITICA.CAPITALIZAR);
    setCantidadCuotas(6);
    setTasaInteres(0);
    setFechaPrimera(dayjs().add(30, "day"));
    setIntervaloDias(30);
    setSimulacion(null);
    setErrorSim(null);
    setMotivo("");
    setDocumentoUrl("");
    setErrorSubmit(null);
  }, [open]);

  // Cargar cuotas pendientes del cliente
  useEffect(() => {
    if (!open || !clienteId) return;
    let cancel = false;
    setLoadingCuotas(true);
    setErrorCuotas(null);
    (async () => {
      try {
        const data = await getCuotasPendientes(clienteId);
        if (cancel) return;
        setCuotas(Array.isArray(data) ? data : []);
      } catch (e) {
        if (cancel) return;
        setErrorCuotas(
          e?.response?.data?.message || "No se pudieron cargar las cuotas",
        );
      } finally {
        if (!cancel) setLoadingCuotas(false);
      }
    })();
    return () => {
      cancel = true;
    };
  }, [open, clienteId, recargaCuotas]);

  const facturaCuotaIds = useMemo(() => {
    const fromSeleccion = Object.entries(seleccion)
      .filter(([, v]) => v)
      .map(([k]) => Number(k))
      .filter(Boolean);
    return fromSeleccion;
  }, [seleccion]);

  const toggleCuota = (id) =>
    setSeleccion((s) => ({ ...s, [id]: !s[id] }));

  const toggleTodas = () => {
    const todas = cuotas.length > 0 && cuotas.every((c) => seleccion[c.id]);
    const next = {};
    if (!todas) cuotas.forEach((c) => (next[c.id] = true));
    setSeleccion(next);
  };

  const puedeAvanzarPaso1 = facturaCuotaIds.length > 0;
  const puedeAvanzarPaso2 = !!politica;
  const puedeAvanzarPaso3 = !!simulacion;
  const puedeConfirmar = motivo.trim().length >= 3 && !!simulacion;

  const handleSimular = async () => {
    if (!clienteId) return;
    if (!facturaCuotaIds.length)
      return toast.error("Seleccioná al menos una cuota");
    if (cantidadCuotas <= 0)
      return toast.error("Cantidad de cuotas debe ser mayor a cero");
    const fechaISO = toFechaCalendarioISO(fechaPrimera);
    if (!fechaISO) return toast.error("Fecha de primera cuota inválida");

    setSimulando(true);
    setErrorSim(null);
    try {
      const data = await simularRefinanciacion({
        cliente_id: clienteId,
        factura_cuota_ids: facturaCuotaIds,
        cantidad_cuotas: Number(cantidadCuotas),
        tasa_interes: Number(tasaInteres),
        fecha_primera_cuota: fechaISO,
        politica_interes: politica,
        intervalo_dias: Number(intervaloDias) || 30,
      });
      setSimulacion(data);
    } catch (e) {
      setErrorSim(
        e?.response?.data?.message || "No se pudo simular la refinanciación",
      );
    } finally {
      setSimulando(false);
    }
  };

  const handleCrear = async () => {
    if (!puedeConfirmar) return;
    setGuardando(true);
    setErrorSubmit(null);
    try {
      const fechaISO = toFechaCalendarioISO(fechaPrimera);
      const refi = await createRefinanciacion({
        cliente_id: clienteId,
        factura_cuota_ids: facturaCuotaIds,
        cantidad_cuotas: Number(cantidadCuotas),
        tasa_interes: Number(tasaInteres),
        fecha_primera_cuota: fechaISO,
        politica_interes: politica,
        intervalo_dias: Number(intervaloDias) || 30,
        motivo: motivo.trim(),
        documento_url: documentoUrl.trim() || undefined,
      });
      toast.success("Refinanciación creada en estado BORRADOR");
      onSuccess?.(refi);
      onClose?.();
    } catch (e) {
      setErrorSubmit(
        e?.response?.data?.message || "No se pudo crear la refinanciación",
      );
    } finally {
      setGuardando(false);
    }
  };

  // ──────────────────────────────────────── Render ──────────────────────────
  return (
    <LocalizationProvider dateAdapter={AdapterDayjs} adapterLocale="es">
    <Dialog open={open} onClose={onClose} maxWidth="md" fullWidth>
      <DialogTitle sx={{ display: "flex", alignItems: "center", gap: 1 }}>
        <Icon icon="mdi:file-restore-outline" width={22} />
        <Typography variant="h6" fontWeight={700} sx={{ flex: 1 }}>
          Nueva refinanciación
        </Typography>
        <IconButton size="small" onClick={onClose}>
          <Icon icon="mdi:close" width={18} />
        </IconButton>
      </DialogTitle>

      <DialogContent dividers>
        <ScreenGuia
          titulo="Refinanciación de deuda"
          intro="Consolidá cuotas vencidas en un nuevo plan. El borrador no impacta saldos hasta ejecutarse."
          pasos={[
            {
              icon: "mdi:counter",
              color: "#1d4ed8",
              titulo: "Elegí qué refinanciar",
              desc: "Seleccioná las cuotas pendientes del cliente que entran al nuevo plan.",
            },
            {
              icon: "mdi:scale-balance",
              color: "#7c3aed",
              titulo: "Política de intereses",
              desc: "Decidí qué pasa con los intereses moratorios: capitalizar, exonerar o mantener.",
            },
            {
              icon: "mdi:calendar-month",
              color: "#059669",
              titulo: "Simulá y confirmá",
              desc: "Calculá el plan, revisá el cronograma y guardá el borrador firmado.",
            },
          ]}
        />

        <Box sx={{ mt: 2 }}>
          <Stepper activeStep={step} alternativeLabel>
            {STEPS.map((label) => (
              <Step key={label}>
                <StepLabel>{label}</StepLabel>
              </Step>
            ))}
          </Stepper>
        </Box>

        <Box sx={{ mt: 3 }}>
          {step === 0 && (
            <Paso1Cuotas
              cuotas={cuotas}
              loading={loadingCuotas}
              error={errorCuotas}
              seleccion={seleccion}
              toggleCuota={toggleCuota}
              toggleTodas={toggleTodas}
              onReintentar={() => setRecargaCuotas((n) => n + 1)}
            />
          )}

          {step === 1 && (
            <Paso2Politica politica={politica} setPolitica={setPolitica} />
          )}

          {step === 2 && (
            <Paso3Plan
              cantidadCuotas={cantidadCuotas}
              setCantidadCuotas={setCantidadCuotas}
              tasaInteres={tasaInteres}
              setTasaInteres={setTasaInteres}
              fechaPrimera={fechaPrimera}
              setFechaPrimera={setFechaPrimera}
              intervaloDias={intervaloDias}
              setIntervaloDias={setIntervaloDias}
              simulando={simulando}
              errorSim={errorSim}
              simulacion={simulacion}
              onSimular={handleSimular}
            />
          )}

          {step === 3 && (
            <Paso4Confirmacion
              simulacion={simulacion}
              motivo={motivo}
              setMotivo={setMotivo}
              documentoUrl={documentoUrl}
              setDocumentoUrl={setDocumentoUrl}
              errorSubmit={errorSubmit}
            />
          )}
        </Box>
      </DialogContent>

      <DialogActions sx={{ px: 3, py: 2 }}>
        <Button onClick={onClose} disabled={guardando}>
          Cancelar
        </Button>
        <Box sx={{ flex: 1 }} />
        <Button
          onClick={() => setStep((s) => Math.max(0, s - 1))}
          disabled={step === 0 || guardando}
        >
          Atrás
        </Button>
        {step < 3 ? (
          <Button
            variant="contained"
            onClick={() => setStep((s) => s + 1)}
            disabled={
              (step === 0 && !puedeAvanzarPaso1) ||
              (step === 1 && !puedeAvanzarPaso2) ||
              (step === 2 && !puedeAvanzarPaso3)
            }
          >
            Siguiente
          </Button>
        ) : (
          <Button
            variant="contained"
            color="primary"
            onClick={handleCrear}
            disabled={!puedeConfirmar || guardando}
            startIcon={
              guardando ? (
                <CircularProgress size={16} color="inherit" />
              ) : (
                <Icon icon="mdi:content-save-outline" />
              )
            }
          >
            Crear borrador
          </Button>
        )}
      </DialogActions>
    </Dialog>
    </LocalizationProvider>
  );
}

// ──────────────────────────────────────────────────────────────────────────────
// Paso 1 — Cuotas
// ──────────────────────────────────────────────────────────────────────────────
function Paso1Cuotas({
  cuotas,
  loading,
  error,
  seleccion,
  toggleCuota,
  toggleTodas,
  onReintentar,
}) {
  if (loading) {
    return (
      <Box sx={{ display: "flex", justifyContent: "center", py: 4 }}>
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Stack spacing={2}>
      {error && (
        <Alert
          severity="error"
          action={
            <Button color="inherit" size="small" onClick={onReintentar}>
              Reintentar
            </Button>
          }
        >
          {error}
        </Alert>
      )}

      {!error && cuotas.length === 0 && (
        <Alert severity="info">El cliente no tiene cuotas pendientes para refinanciar.</Alert>
      )}

      {cuotas.length > 0 && (
        <Paper variant="outlined">
          <Box
            sx={{
              px: 1.5,
              py: 1,
              display: "flex",
              alignItems: "center",
              gap: 1,
              borderBottom: "1px solid",
              borderColor: "divider",
            }}
          >
            <FormControlLabel
              control={
                <Checkbox
                  size="small"
                  checked={
                    cuotas.length > 0 &&
                    cuotas.every((c) => seleccion[c.id])
                  }
                  indeterminate={
                    cuotas.some((c) => seleccion[c.id]) &&
                    !cuotas.every((c) => seleccion[c.id])
                  }
                  onChange={toggleTodas}
                />
              }
              label={
                <Typography variant="caption" fontWeight={600}>
                  Seleccionar todas
                </Typography>
              }
            />
            <Box sx={{ flex: 1 }} />
            <Typography variant="caption" color="text.secondary">
              {Object.values(seleccion).filter(Boolean).length} seleccionada(s)
            </Typography>
          </Box>
          <TableContainer sx={{ maxHeight: 320 }}>
            <Table size="small" stickyHeader>
              <TableHead>
                <TableRow>
                  <TableCell padding="checkbox" />
                  <TableCell>Factura</TableCell>
                  <TableCell>Cuota</TableCell>
                  <TableCell>Vencimiento</TableCell>
                  <TableCell align="right">Saldo</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {cuotas.map((c) => {
                  const fact = c.factura_cab || c.factura;
                  const nroFactura = fact
                    ? `${fact.dest ?? ""}-${fact.dpunexp ?? ""}-${fact.dnumdoc ?? ""}`
                    : "Sin número";
                  return (
                    <TableRow
                      key={c.id}
                      hover
                      onClick={() => toggleCuota(c.id)}
                      sx={{ cursor: "pointer" }}
                    >
                      <TableCell padding="checkbox">
                        <Checkbox
                          size="small"
                          checked={!!seleccion[c.id]}
                          onChange={() => toggleCuota(c.id)}
                          onClick={(e) => e.stopPropagation()}
                        />
                      </TableCell>
                      <TableCell sx={{ fontFamily: "monospace", fontSize: "0.8rem" }}>
                        {nroFactura}
                      </TableCell>
                      <TableCell>{c.nro_cuota ?? "—"}</TableCell>
                      <TableCell>{fmtFechaCalendario(c.dvenccuo)}</TableCell>
                      <TableCell align="right">
                        {fmtGs(c.saldo_pendiente ?? c.dmoncuota)} Gs.
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          </TableContainer>
        </Paper>
      )}

    </Stack>
  );
}

// ──────────────────────────────────────────────────────────────────────────────
// Paso 2 — Política de intereses
// ──────────────────────────────────────────────────────────────────────────────
function Paso2Politica({ politica, setPolitica }) {
  const items = Object.entries(COB_REFI_POLITICA_META).map(([key, meta]) => ({
    key,
    label: `${meta.label}: ${meta.desc}`,
    ok: politica === key,
  }));

  return (
    <Stack spacing={2}>
      <PrereqChecklist
        title="Implicancias de cada política"
        items={items}
      />
      <Paper variant="outlined" sx={{ p: 2 }}>
        <Typography variant="subtitle2" fontWeight={600} sx={{ mb: 1 }}>
          Política a aplicar
        </Typography>
        <RadioGroup
          value={politica}
          onChange={(e) => setPolitica(e.target.value)}
        >
          {Object.entries(COB_REFI_POLITICA_META).map(([key, meta]) => (
            <FormControlLabel
              key={key}
              value={key}
              control={<Radio />}
              label={
                <Box>
                  <Typography variant="body2" fontWeight={600}>
                    {meta.label}
                  </Typography>
                  <Typography variant="caption" color="text.secondary">
                    {meta.desc}
                  </Typography>
                </Box>
              }
              sx={{ alignItems: "flex-start", mb: 1 }}
            />
          ))}
        </RadioGroup>
      </Paper>
    </Stack>
  );
}

// ──────────────────────────────────────────────────────────────────────────────
// Paso 3 — Nuevo plan + simulación
// ──────────────────────────────────────────────────────────────────────────────
function Paso3Plan({
  cantidadCuotas,
  setCantidadCuotas,
  tasaInteres,
  setTasaInteres,
  fechaPrimera,
  setFechaPrimera,
  intervaloDias,
  setIntervaloDias,
  simulando,
  errorSim,
  simulacion,
  onSimular,
}) {
  return (
    <Stack spacing={2}>
      <Paper variant="outlined" sx={{ p: 2 }}>
        <Stack direction={{ xs: "column", sm: "row" }} spacing={2}>
          <TextField
            label="Cantidad de cuotas"
            type="number"
            size="small"
            value={cantidadCuotas}
            onChange={(e) =>
              setCantidadCuotas(Math.max(1, Number(e.target.value) || 0))
            }
            inputProps={{ min: 1, max: 120 }}
            sx={{ flex: 1 }}
          />
          <TextField
            label="Tasa de interés (% anual)"
            type="number"
            size="small"
            value={tasaInteres}
            onChange={(e) => setTasaInteres(Number(e.target.value) || 0)}
            inputProps={{ min: 0, step: 0.1 }}
            sx={{ flex: 1 }}
          />
          <DatePicker
            label="Fecha primera cuota"
            value={fechaPrimera}
            onChange={(v) => setFechaPrimera(v)}
            slotProps={{ textField: { size: "small", sx: { flex: 1 } } }}
          />
          <TextField
            label="Intervalo (días)"
            type="number"
            size="small"
            value={intervaloDias}
            onChange={(e) =>
              setIntervaloDias(Math.max(1, Number(e.target.value) || 30))
            }
            inputProps={{ min: 1 }}
            sx={{ flex: 1 }}
          />
        </Stack>
        <Box sx={{ mt: 2, display: "flex", justifyContent: "flex-end" }}>
          <Button
            variant="contained"
            onClick={onSimular}
            disabled={simulando}
            startIcon={
              simulando ? (
                <CircularProgress size={16} color="inherit" />
              ) : (
                <Icon icon="mdi:calculator" />
              )
            }
          >
            Simular
          </Button>
        </Box>
      </Paper>

      {errorSim && <Alert severity="error">{errorSim}</Alert>}

      {simulacion && <SimulacionPreview simulacion={simulacion} />}
    </Stack>
  );
}

function SimulacionPreview({ simulacion }) {
  const {
    monto_capital_orig,
    monto_interes_orig,
    monto_interes_exon,
    monto_capital_nuevo,
    monto_cuota,
    cuotas_propuestas = [],
  } = simulacion;

  return (
    <Paper variant="outlined" sx={{ p: 2 }}>
      <Typography variant="subtitle2" fontWeight={700} sx={{ mb: 1.5 }}>
        Resultado de la simulación
      </Typography>
      <Stack direction="row" spacing={1} flexWrap="wrap" sx={{ mb: 2, rowGap: 1 }}>
        <ResumenChip
          label="Capital original"
          value={monto_capital_orig}
          color="default"
        />
        <ResumenChip
          label="Intereses originales"
          value={monto_interes_orig}
          color="warning"
        />
        {Number(monto_interes_exon) > 0 && (
          <ResumenChip
            label="Intereses exonerados"
            value={monto_interes_exon}
            color="error"
          />
        )}
        <ResumenChip
          label="Capital nuevo"
          value={monto_capital_nuevo}
          color="success"
          strong
        />
        <ResumenChip label="Monto cuota" value={monto_cuota} color="info" />
      </Stack>

      <TableContainer sx={{ maxHeight: 260 }}>
        <Table size="small" stickyHeader>
          <TableHead>
            <TableRow>
              <TableCell>Cuota</TableCell>
              <TableCell>Vencimiento</TableCell>
              <TableCell align="right">Monto</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {cuotas_propuestas.map((c) => (
              <TableRow key={c.nro_cuota}>
                <TableCell>{c.nro_cuota}</TableCell>
                <TableCell>{fmtFechaCalendario(c.fecha_vencimiento)}</TableCell>
                <TableCell align="right">{fmtGs(c.monto_cuota)} Gs.</TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>
    </Paper>
  );
}

function ResumenChip({ label, value, color = "default", strong = false }) {
  return (
    <Paper
      variant="outlined"
      sx={{
        px: 1.25,
        py: 0.75,
        borderColor: strong ? "success.main" : undefined,
        bgcolor: strong ? "success.50" : "background.paper",
      }}
    >
      <Typography variant="caption" color="text.secondary" display="block">
        {label}
      </Typography>
      <Typography
        variant="body2"
        fontWeight={strong ? 700 : 600}
        color={strong ? "success.main" : "text.primary"}
      >
        {fmtGs(value)} Gs.
      </Typography>
    </Paper>
  );
}

// ──────────────────────────────────────────────────────────────────────────────
// Paso 4 — Confirmación
// ──────────────────────────────────────────────────────────────────────────────
function Paso4Confirmacion({
  simulacion,
  motivo,
  setMotivo,
  documentoUrl,
  setDocumentoUrl,
  errorSubmit,
}) {
  if (!simulacion)
    return (
      <Alert severity="warning">
        Volvé al paso anterior y simulá el plan antes de confirmar.
      </Alert>
    );

  return (
    <Stack spacing={2}>
      <Alert severity="info" icon={<Icon icon="mdi:information-outline" />}>
        Se creará un borrador. Para que impacte en los saldos del cliente deberá
        ejecutarse desde la pantalla de refinanciaciones.
      </Alert>

      <Paper variant="outlined" sx={{ p: 2 }}>
        <Stack direction="row" spacing={2} flexWrap="wrap" sx={{ rowGap: 1 }}>
          <Chip
            size="small"
            label={`${simulacion.cantidad_cuotas} cuotas`}
            color="primary"
          />
          <Chip
            size="small"
            label={`Capital nuevo: ${fmtGs(simulacion.monto_capital_nuevo)} Gs.`}
            color="success"
          />
          <Chip
            size="small"
            label={`Política: ${simulacion.politica_interes}`}
          />
        </Stack>
      </Paper>

      <TextField
        label="Motivo"
        required
        multiline
        minRows={3}
        value={motivo}
        onChange={(e) => setMotivo(e.target.value)}
        helperText="Ej: cliente atravesando dificultad financiera transitoria; acuerda nuevo plan a 12 meses."
      />

      <TextField
        label="Documento firmado (URL)"
        value={documentoUrl}
        onChange={(e) => setDocumentoUrl(e.target.value)}
        helperText="Opcional. Subí el PDF firmado a tu repositorio y pegá la URL."
      />

      {errorSubmit && (
        <InlineValidationBanner
          title="No se pudo crear la refinanciación"
          errors={[errorSubmit]}
        />
      )}
    </Stack>
  );
}

export default RefinanciacionWizard;
