"use client";

import { useEffect, useMemo, useState } from "react";
import { AlertCircle, RefreshCw, Plus, XCircle } from "lucide-react";

type RepactacionRow = {
  Id_repactacion: number;
  Id_cliente: number;
  Id_boleta_inicio: number;
  Id_boleta_termino: number;
  pie_repac: number;
  valor_cuota: number;
  no_cuotas: number;
  ult_cuota_facturada: number;
  ult_cuota_pagada: number;
  monto_total: number;
  porcentaje_interes: number;
  interes_total: number;
  estado_repactacion: number;
  nombre_cliente?: string;
  rut_cliente?: string;
};

type Preview = {
  monto_repac: number;
  monto_total: number;
  interes_total: number;
  valor_cuota: number;
};

export default function RepactacionesPage() {
  const [loading, setLoading] = useState(true);
  const [working, setWorking] = useState(false);
  const [mensaje, setMensaje] = useState<{ tipo: "error" | "success"; texto: string } | null>(null);

  const [tab, setTab] = useState<"activas" | "historico">("activas");
  const [repactaciones, setRepactaciones] = useState<RepactacionRow[]>([]);

  const [Id_cliente, setIdCliente] = useState("");
  const [Id_boleta_inicio, setIdBoletaInicio] = useState("");
  const [Id_boleta_termino, setIdBoletaTermino] = useState("");
  const [pie_repac, setPieRepac] = useState("0");
  const [no_cuotas, setNoCuotas] = useState("12");
  const [porcentaje_interes, setPorcentajeInteres] = useState("0");

  const [preview, setPreview] = useState<Preview | null>(null);

  const canCreate = useMemo(() => {
    return Boolean(Id_cliente && Id_boleta_inicio && Id_boleta_termino && no_cuotas);
  }, [Id_cliente, Id_boleta_inicio, Id_boleta_termino, no_cuotas]);

  const cargar = async () => {
    setLoading(true);
    setMensaje(null);
    try {
      const qs = tab === "historico" ? "historico=true" : "activas=true";
      const res = await fetch(`/api/repactaciones?${qs}`);
      const data = await res.json();
      if (!res.ok) throw new Error(data?.error || "Error al cargar repactaciones");
      setRepactaciones(data);
    } catch (e: any) {
      setMensaje({ tipo: "error", texto: e?.message || "Error al cargar repactaciones" });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    void cargar();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [tab]);

  const autocompletarRangoBoletas = async () => {
    setMensaje(null);
    setPreview(null);
    if (!Id_cliente) {
      setMensaje({ tipo: "error", texto: "Debe ingresar Id_cliente" });
      return;
    }

    setWorking(true);
    try {
      const res = await fetch(`/api/repactaciones?clienteId=${encodeURIComponent(Id_cliente)}&rango=true`);
      const data = await res.json();
      if (!res.ok) throw new Error(data?.error || "Error al obtener rango de boletas");

      setIdBoletaInicio(data?.min_id_boleta ? String(data.min_id_boleta) : "");
      setIdBoletaTermino(data?.max_id_boleta ? String(data.max_id_boleta) : "");
    } catch (e: any) {
      setMensaje({ tipo: "error", texto: e?.message || "Error al obtener rango de boletas" });
    } finally {
      setWorking(false);
    }
  };

  const recalcularPreview = async () => {
    setMensaje(null);
    if (!Id_cliente) return;

    try {
      const url = `/api/repactaciones?clienteId=${encodeURIComponent(Id_cliente)}&preview=true&pie_repac=${encodeURIComponent(
        pie_repac || "0"
      )}&no_cuotas=${encodeURIComponent(no_cuotas || "0")}&porcentaje_interes=${encodeURIComponent(
        porcentaje_interes || "0"
      )}`;
      const res = await fetch(url);
      const data = await res.json();
      if (!res.ok) throw new Error(data?.error || "Error al calcular preview");
      setPreview(data);
    } catch (e: any) {
      setPreview(null);
    }
  };

  useEffect(() => {
    void recalcularPreview();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [Id_cliente, pie_repac, no_cuotas, porcentaje_interes]);

  const crear = async () => {
    setWorking(true);
    setMensaje(null);
    try {
      if (!canCreate) {
        setMensaje({ tipo: "error", texto: "Datos incompletos" });
        return;
      }

      const res = await fetch("/api/repactaciones", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          Id_cliente: Number(Id_cliente),
          Id_boleta_inicio: Number(Id_boleta_inicio),
          Id_boleta_termino: Number(Id_boleta_termino),
          pie_repac: Number(pie_repac || 0),
          no_cuotas: Number(no_cuotas),
          porcentaje_interes: Number(porcentaje_interes || 0),
        }),
      });

      const data = await res.json();
      if (!res.ok) throw new Error(data?.error || "Error al crear repactación");

      setMensaje({ tipo: "success", texto: data?.message || "Repactación creada" });
      setTab("activas");
      setIdCliente("");
      setIdBoletaInicio("");
      setIdBoletaTermino("");
      setPieRepac("0");
      setNoCuotas("12");
      setPorcentajeInteres("0");
      setPreview(null);
      await cargar();
    } catch (e: any) {
      setMensaje({ tipo: "error", texto: e?.message || "Error al crear repactación" });
    } finally {
      setWorking(false);
    }
  };

  const cerrar = async (id: number) => {
    const ok = confirm("¿Está seguro de cerrar esta repactación?");
    if (!ok) return;

    setWorking(true);
    setMensaje(null);
    try {
      const res = await fetch("/api/repactaciones", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id, accion: "cerrar" }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data?.error || "Error al cerrar repactación");
      setMensaje({ tipo: "success", texto: data?.message || "Repactación cerrada" });
      await cargar();
    } catch (e: any) {
      setMensaje({ tipo: "error", texto: e?.message || "Error al cerrar repactación" });
    } finally {
      setWorking(false);
    }
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold text-gray-900">Repactaciones</h1>
        <p className="mt-1 text-sm text-gray-500">Gestión de convenios de pago y deudas repactadas.</p>
      </div>

      {mensaje && (
        <div
          className={`rounded-md p-4 border ${
            mensaje.tipo === "error" ? "bg-red-50 border-red-200" : "bg-green-50 border-green-200"
          }`}
        >
          <div className="flex">
            <div className="flex-shrink-0">
              {mensaje.tipo === "error" ? (
                <AlertCircle className="h-5 w-5 text-red-400" />
              ) : (
                <RefreshCw className="h-5 w-5 text-green-400" />
              )}
            </div>
            <div className="ml-3">
              <p className={`text-sm ${mensaje.tipo === "error" ? "text-red-700" : "text-green-700"}`}>
                {mensaje.texto}
              </p>
            </div>
          </div>
        </div>
      )}

      <div className="flex gap-2">
        <button
          className={`px-3 py-2 rounded-md text-sm border ${
            tab === "activas" ? "bg-gray-900 text-white border-gray-900" : "bg-white text-gray-700 border-gray-200"
          }`}
          onClick={() => setTab("activas")}
          disabled={working}
        >
          Activas
        </button>
        <button
          className={`px-3 py-2 rounded-md text-sm border ${
            tab === "historico" ? "bg-gray-900 text-white border-gray-900" : "bg-white text-gray-700 border-gray-200"
          }`}
          onClick={() => setTab("historico")}
          disabled={working}
        >
          Histórico
        </button>
        <button
          className="ml-auto inline-flex items-center px-3 py-2 rounded-md text-sm border border-gray-200 bg-white text-gray-700 hover:bg-gray-50"
          onClick={() => void cargar()}
          disabled={working}
        >
          <RefreshCw className={`h-4 w-4 mr-2 ${working ? "animate-spin" : ""}`} />
          Recargar
        </button>
      </div>

      <div className="bg-white shadow sm:rounded-lg p-4">
        <h2 className="text-lg font-semibold text-gray-900">Nueva repactación</h2>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mt-4">
          <div>
            <label className="block text-sm font-medium text-gray-700">Id_cliente</label>
            <input
              className="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
              value={Id_cliente}
              onChange={(e) => setIdCliente(e.target.value)}
              disabled={working}
              inputMode="numeric"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700">Pie</label>
            <input
              className="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
              value={pie_repac}
              onChange={(e) => setPieRepac(e.target.value)}
              disabled={working}
              inputMode="numeric"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700">N° cuotas</label>
            <input
              className="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
              value={no_cuotas}
              onChange={(e) => setNoCuotas(e.target.value)}
              disabled={working}
              inputMode="numeric"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700">% interés</label>
            <input
              className="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
              value={porcentaje_interes}
              onChange={(e) => setPorcentajeInteres(e.target.value)}
              disabled={working}
              inputMode="numeric"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700">Boleta inicio</label>
            <input
              className="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
              value={Id_boleta_inicio}
              onChange={(e) => setIdBoletaInicio(e.target.value)}
              disabled={working}
              inputMode="numeric"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700">Boleta término</label>
            <input
              className="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
              value={Id_boleta_termino}
              onChange={(e) => setIdBoletaTermino(e.target.value)}
              disabled={working}
              inputMode="numeric"
            />
          </div>
        </div>

        <div className="flex flex-wrap gap-2 mt-4">
          <button
            className="inline-flex items-center px-3 py-2 rounded-md text-sm bg-white border border-gray-200 text-gray-700 hover:bg-gray-50"
            onClick={() => void autocompletarRangoBoletas()}
            disabled={working || !Id_cliente}
          >
            <RefreshCw className="h-4 w-4 mr-2" />
            Rellenar rango boletas
          </button>

          <button
            className="inline-flex items-center px-3 py-2 rounded-md text-sm bg-indigo-600 text-white hover:bg-indigo-700 disabled:opacity-50"
            onClick={() => void crear()}
            disabled={working || !canCreate}
          >
            <Plus className="h-4 w-4 mr-2" />
            Crear
          </button>
        </div>

        {preview && (
          <div className="mt-4 rounded-md border border-gray-200 bg-gray-50 p-3 text-sm">
            <div className="grid grid-cols-1 md:grid-cols-4 gap-2">
              <div>
                <div className="text-gray-500">Deuda (monto_repac)</div>
                <div className="font-semibold">${preview.monto_repac?.toLocaleString("es-CL")}</div>
              </div>
              <div>
                <div className="text-gray-500">Interés total</div>
                <div className="font-semibold">${preview.interes_total?.toLocaleString("es-CL")}</div>
              </div>
              <div>
                <div className="text-gray-500">Monto total</div>
                <div className="font-semibold">${preview.monto_total?.toLocaleString("es-CL")}</div>
              </div>
              <div>
                <div className="text-gray-500">Valor cuota</div>
                <div className="font-semibold">${preview.valor_cuota?.toLocaleString("es-CL")}</div>
              </div>
            </div>
          </div>
        )}
      </div>

      <div className="bg-white shadow sm:rounded-lg overflow-hidden">
        <div className="px-4 py-3 border-b border-gray-200 flex items-center">
          <h2 className="text-lg font-semibold text-gray-900">
            {tab === "activas" ? "Repactaciones activas" : "Histórico"}
          </h2>
          {loading && <span className="ml-3 text-sm text-gray-500">Cargando...</span>}
        </div>

        <div className="overflow-x-auto">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Cliente</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Boletas</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Cuotas</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Monto</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Estado</th>
                <th className="px-4 py-3"></th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {repactaciones.map((r) => {
                const estado = Number(r.estado_repactacion) === 0 ? "Activa" : "Cerrada";
                return (
                  <tr key={r.Id_repactacion}>
                    <td className="px-4 py-3 whitespace-nowrap">
                      <div className="text-sm font-medium text-gray-900">{r.nombre_cliente || `#${r.Id_cliente}`}</div>
                      <div className="text-xs text-gray-500">{r.rut_cliente || ""}</div>
                    </td>
                    <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-700">
                      {r.Id_boleta_inicio} - {r.Id_boleta_termino}
                    </td>
                    <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-700">
                      {r.ult_cuota_facturada} / {r.no_cuotas}
                    </td>
                    <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-700">
                      <div className="font-semibold">${Number(r.monto_total || 0).toLocaleString("es-CL")}</div>
                      <div className="text-xs text-gray-500">
                        Cuota: ${Number(r.valor_cuota || 0).toLocaleString("es-CL")}
                      </div>
                    </td>
                    <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-700">{estado}</td>
                    <td className="px-4 py-3 whitespace-nowrap text-right">
                      {tab === "activas" && (
                        <button
                          className="inline-flex items-center px-3 py-2 rounded-md text-sm bg-white border border-gray-200 text-gray-700 hover:bg-gray-50"
                          onClick={() => void cerrar(r.Id_repactacion)}
                          disabled={working}
                        >
                          <XCircle className="h-4 w-4 mr-2" />
                          Cerrar
                        </button>
                      )}
                    </td>
                  </tr>
                );
              })}

              {!loading && repactaciones.length === 0 && (
                <tr>
                  <td colSpan={6} className="px-4 py-10 text-center text-gray-500">
                    No hay repactaciones.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
