"use client";

import React, { useState } from 'react';
import { formCambiarEstadoContacto, formCambiarEstadoPago, formCambiarEstadoPagoReporte } from '@/app/actions/inscripciones-admin';
import { useRouter } from 'next/navigation';
import { Check, X, Phone, DollarSign, ExternalLink } from 'lucide-react';

export function PagosTable({ reportes, pagos }: { reportes: any[], pagos: any[] }) {
  const router = useRouter();
  const [loadingId, setLoadingId] = useState<string | null>(null);

  const handleAction = async (actionFn: Function, id: string, label: string) => {
    if (!confirm(`¿Estás seguro de ${label}?`)) return;
    setLoadingId(id);
    await actionFn();
    router.refresh();
    setLoadingId(null);
  };

  return (
    <div className="flex flex-col gap-6">
      {/* SECCIÓN 1: Reportes de Pago por Validar */}
      <div className="bg-white p-6 shadow-sm rounded-xl border border-gray-100 mb-6">
        <h2 className="text-2xl font-extrabold text-gray-800 tracking-tight mb-2">
          Validación de Pagos (Reportes Subidos)
        </h2>
        <p className="text-gray-500 mb-6 text-sm">
          Pagos y captures reportados por estudiantes para distintas clases o cuotas.
        </p>

        <div className="overflow-x-auto rounded-lg border border-gray-200">
          <table className="w-full text-left text-sm text-gray-500 bg-white">
            <thead className="bg-[#1e2a47] text-white uppercase font-semibold text-xs">
              <tr>
                <th className="px-6 py-4">Estudiante / Curso</th>
                <th className="px-6 py-4">Concepto / Fecha</th>
                <th className="px-6 py-4">Comprobante</th>
                <th className="px-6 py-4 text-center">Estado Pago</th>
                <th className="px-6 py-4 text-right">Acciones</th>
              </tr>
            </thead>
            <tbody>
              {reportes.map((rep) => (
                <tr key={rep.id} className="border-b border-gray-100 hover:bg-gray-50 transition-colors">
                  <td className="px-6 py-4">
                    <div className="font-bold text-gray-800 text-sm">{rep.inscripcion.user.name} {rep.inscripcion.user.apellido || ""}</div>
                    <div className="text-xs font-semibold text-blue-600">{rep.inscripcion.curso.titulo}</div>
                  </td>
                  <td className="px-6 py-4 text-sm font-semibold text-gray-700">
                    <div>{rep.concepto} - Bs/USD {rep.monto}</div>
                    <div className="text-xs text-gray-500 font-medium">Ref: {rep.referencia} | {rep.fechaPago}</div>
                  </td>
                  <td className="px-6 py-4">
                    <a href={rep.comprobanteUrl} target="_blank" rel="noopener noreferrer" 
                       className="text-[#0066ff] hover:text-blue-700 font-bold text-xs flex items-center gap-1 transition-colors">
                      Ver Capture <ExternalLink className="w-3 h-3" />
                    </a>
                  </td>
                  <td className="px-6 py-4 text-center">
                    <span className={`px-3 py-1 rounded-full text-[10px] font-extrabold whitespace-nowrap tracking-wider ${
                      rep.estado === 'APROBADO' ? 'bg-green-100 text-green-700' :
                      rep.estado === 'RECHAZADO' ? 'bg-red-100 text-red-700' :
                      'bg-yellow-100 text-yellow-700'
                    }`}>
                      {rep.estado}
                    </span>
                  </td>
                  <td className="px-6 py-4 text-right">
                    {rep.estado === 'PENDIENTE' && (
                      <div className="flex gap-2 justify-end">
                        <button 
                          disabled={loadingId === rep.id}
                          onClick={() => handleAction(() => formCambiarEstadoPagoReporte(rep.id, "APROBADO"), rep.id, "APROBAR este pago")}
                          className="bg-green-500 hover:bg-green-600 text-white px-3 py-1.5 rounded-md font-bold text-xs shadow-sm transition-all flex items-center gap-1 disabled:opacity-50">
                          {loadingId === rep.id ? <span className="animate-spin text-[8px]">⟳</span> : <Check className="w-3 h-3" />}
                          Aprobar
                        </button>
                        <button 
                          disabled={loadingId === rep.id}
                          onClick={() => handleAction(() => formCambiarEstadoPagoReporte(rep.id, "RECHAZADO"), rep.id, "RECHAZAR este pago")}
                          className="bg-red-500 hover:bg-red-600 text-white px-3 py-1.5 rounded-md font-bold text-xs shadow-sm transition-all flex items-center gap-1 disabled:opacity-50">
                          {loadingId === rep.id ? <span className="animate-spin text-[8px]">⟳</span> : <X className="w-3 h-3" />}
                          Rechazar
                        </button>
                      </div>
                    )}
                  </td>
                </tr>
              ))}
              {reportes.length === 0 && (
                <tr>
                   <td colSpan={5} className="px-6 py-12 text-center text-gray-400 font-semibold italic">
                      No hay pagos reportados todavía.
                   </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      <div className="bg-white p-6 shadow-sm rounded-xl border border-gray-100">
        <h2 className="text-2xl font-extrabold text-gray-800 tracking-tight mb-2">
          Gestión de Inscripciones y Primeros Contactos
        </h2>
        <p className="text-gray-500 mb-6 text-sm">
          Registros recientes desde la web. Recuerda contactar primero a los nuevos estudiantes (PENDIENTE_CONTACTAR).
        </p>

        <div className="overflow-x-auto rounded-lg border border-gray-200">
          <table className="w-full text-left text-sm text-gray-500 bg-white">
            <thead className="bg-[#1e2a47] text-white uppercase font-semibold text-xs">
              <tr>
                <th className="px-6 py-4">Inscrito (Teléfono)</th>
                <th className="px-6 py-4">Curso Objetivo</th>
                <th className="px-6 py-4 text-center">Estado Contacto</th>
                <th className="px-6 py-4 text-center">Estado Pago Total</th>
                <th className="px-6 py-4 text-right">Acciones</th>
              </tr>
            </thead>
            <tbody>
              {pagos.map((pago) => (
                <tr key={pago.id} className="border-b border-gray-100 hover:bg-gray-50 transition-colors">
                  <td className="px-6 py-4">
                    <div className="font-bold text-gray-800 text-sm">{pago.user.name} {pago.user.apellido || ""}</div>
                    <div className="text-xs font-semibold text-[#0066ff]">📞 {pago.user.telefono || "Sin Tlf"}</div>
                  </td>
                  <td className="px-6 py-4 font-semibold text-gray-800">
                    {pago.curso.titulo}
                  </td>
                  
                  <td className="px-6 py-4 text-center">
                    <span className={`px-3 py-1 rounded-full text-[10px] font-extrabold whitespace-nowrap tracking-wider ${
                      pago.estadoFlujo === 'PENDIENTE_CONTACTAR' ? 'bg-orange-100 text-orange-700' :
                      pago.estadoFlujo === 'CONTACTADO' ? 'bg-blue-100 text-blue-700' :
                      'bg-purple-100 text-purple-700'
                    }`}>
                      {pago.estadoFlujo.replace(/_/g, " ")}
                    </span>
                  </td>

                  <td className="px-6 py-4 text-center">
                    <span className={`px-3 py-1 rounded-full text-[10px] font-extrabold whitespace-nowrap tracking-wider ${
                      pago.estadoPago === 'APROBADO' ? 'bg-green-100 text-green-700' :
                      pago.estadoPago === 'RECHAZADO' ? 'bg-red-100 text-red-700' :
                      'bg-yellow-100 text-yellow-700'
                    }`}>
                      {pago.estadoPago}
                    </span>
                  </td>

                  <td className="px-6 py-4 text-right">
                     <div className="flex gap-2 justify-end flex-wrap items-center">
                        {pago.estadoFlujo === 'PENDIENTE_CONTACTAR' && (
                          <button 
                            disabled={loadingId === pago.id}
                            onClick={() => handleAction(() => formCambiarEstadoContacto(pago.id, "CONTACTADO"), pago.id, "marcar como CONTACTADO")}
                            className="bg-orange-500 hover:bg-orange-600 text-white px-3 py-1.5 rounded-md font-bold text-xs transition shadow-sm flex items-center gap-1 disabled:opacity-50">
                            {loadingId === pago.id ? <span className="animate-spin text-[8px]">⟳</span> : <Phone className="w-3 h-3" />}
                            Contactado
                          </button>
                        )}

                        {pago.estadoPago === 'PENDIENTE' && (
                          <button 
                            disabled={loadingId === pago.id}
                            onClick={() => handleAction(() => formCambiarEstadoPago(pago.id, "APROBADO"), pago.id, "APROBAR el pago total")}
                            className="bg-green-500 hover:bg-green-600 text-white px-3 py-1.5 rounded-md font-bold text-xs transition shadow-sm flex items-center gap-1 disabled:opacity-50">
                            {loadingId === pago.id ? <span className="animate-spin text-[8px]">⟳</span> : <DollarSign className="w-3 h-3" />}
                            Aprobar
                          </button>
                        )}
                        
                        {(pago.estadoFlujo !== 'PENDIENTE_CONTACTAR' && pago.estadoPago !== 'PENDIENTE') && (
                          <span className="text-gray-400 font-bold text-[11px] uppercase">Al Día</span>
                        )}
                     </div>
                  </td>
                </tr>
              ))}

              {pagos.length === 0 && (
                <tr>
                   <td colSpan={5} className="px-6 py-12 text-center text-gray-400 font-semibold italic">
                      No hay inscripciones ni pagos procesados todavía.
                   </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
