"use client";

import { useState } from "react";
import { Check, X, AlertCircle, Save, Loader2, CheckCircle2 } from "lucide-react";
import { registrarAsistenciaBlock } from "@/app/actions/asistencia";

type AlumnoRow = {
  inscripcionId: string;
  nombre: string;
  telefono: string;
  status: string;
  asistio: boolean;
  pagoDebe: boolean;
  observacion: string;
};

export default function AsistenciaClient({ claseId, alumnosIniciales }: { claseId: string, alumnosIniciales: AlumnoRow[] }) {
  const [alumnos, setAlumnos] = useState<AlumnoRow[]>(alumnosIniciales);
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);

  const toggleAsistencia = (id: string) => {
    setAlumnos(prev => prev.map(a => a.inscripcionId === id ? { ...a, asistio: !a.asistio } : a));
  };

  const togglePagoDebe = (id: string) => {
    setAlumnos(prev => prev.map(a => a.inscripcionId === id ? { ...a, pagoDebe: !a.pagoDebe } : a));
  };

  const handleObservacion = (id: string, text: string) => {
    setAlumnos(prev => prev.map(a => a.inscripcionId === id ? { ...a, observacion: text } : a));
  };

  const handleSubmit = async () => {
    setLoading(true);
    setSuccess(false);
    try {
      await registrarAsistenciaBlock(
        claseId, 
        alumnos.map(a => ({
          inscripcionId: a.inscripcionId,
          asistio: a.asistio,
          pagoDebe: a.pagoDebe,
          observacion: a.observacion
        }))
      );
      setSuccess(true);
      setTimeout(() => setSuccess(false), 3000);
    } catch (e) {
      console.error(e);
      alert("Error al guardar asistencia. Actualiza la página e inténtalo de nuevo.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex flex-col gap-6">
      <div className="flex items-center justify-between">
        <h2 className="text-xl font-bold text-gray-800">Listado de Inscritos</h2>
        <button 
          onClick={handleSubmit} 
          disabled={loading}
          className="bg-[#0066ff] hover:bg-blue-600 px-5 py-2.5 rounded-lg text-white font-bold flex items-center gap-2 transition-colors disabled:opacity-50"
        >
          {loading ? <Loader2 className="w-5 h-5 animate-spin" /> : <Save className="w-5 h-5" />}
          Guardar Cambios
        </button>
      </div>

      {success && (
        <div className="bg-green-50 z-10 border border-green-200 text-green-700 px-4 py-3 rounded-lg flex items-center gap-2 font-semibold">
          <CheckCircle2 className="w-5 h-5" />
          ¡Asistencia registrada y guardada exitosamente!
        </div>
      )}

      {alumnos.length === 0 ? (
        <div className="text-center py-10 bg-gray-50 border border-gray-100 rounded-xl text-gray-500 font-semibold">
          No hay estudiantes inscritos en este curso todavía.
        </div>
      ) : (
        <div className="overflow-x-auto rounded-xl border border-gray-200">
          <table className="w-full text-left text-sm text-gray-600">
            <thead className="bg-[#1e2a47] text-white whitespace-nowrap">
              <tr>
                <th className="px-6 py-4 font-bold uppercase tracking-wider text-xs">A/F</th>
                <th className="px-6 py-4 font-bold uppercase tracking-wider text-xs">Debe Clase</th>
                <th className="px-6 py-4 font-bold uppercase tracking-wider text-xs w-1/3">Estudiante</th>
                <th className="px-6 py-4 font-bold uppercase tracking-wider text-xs">Contacto</th>
                <th className="px-6 py-4 font-bold uppercase tracking-wider text-xs">Observación</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100 bg-white">
              {alumnos.map((alum) => (
                <tr key={alum.inscripcionId} className="hover:bg-gray-50/50 transition-colors">
                  <td className="px-6 py-4">
                    <button 
                      onClick={() => toggleAsistencia(alum.inscripcionId)}
                      className={`w-10 h-10 rounded-full flex items-center justify-center border-2 transition-all shadow-sm ${
                        alum.asistio 
                          ? "bg-green-100 border-green-500 text-green-600" 
                          : "bg-red-100 border-red-500 text-red-600"
                      }`}
                      title={alum.asistio ? "Asistió - Clic para marcar Falta" : "Faltó - Clic para marcar Asistencia"}
                    >
                      {alum.asistio ? <Check className="w-5 h-5" /> : <X className="w-5 h-5" />}
                    </button>
                  </td>
                  
                  <td className="px-6 py-4">
                    <button 
                      onClick={() => togglePagoDebe(alum.inscripcionId)}
                      className={`px-3 py-1.5 rounded-md text-xs font-bold border transition-colors flex items-center gap-1.5 ${
                        alum.pagoDebe 
                          ? "bg-red-50 text-red-700 border-red-200" 
                          : "bg-gray-50 text-gray-400 border-gray-200 hover:bg-gray-100"
                      }`}
                    >
                      {alum.pagoDebe ? <AlertCircle className="w-3.5 h-3.5" /> : null}
                      {alum.pagoDebe ? "SI DEBE" : "No Debe"}
                    </button>
                  </td>

                  <td className="px-6 py-4">
                    <div className="font-bold text-gray-900 text-base">{alum.nombre}</div>
                    {alum.status === "MOROSO" && (
                       <span className="text-[10px] uppercase font-bold bg-red-100 text-red-700 px-2 py-0.5 rounded mt-1 inline-block">Moroso Global</span>
                    )}
                  </td>
                  
                  <td className="px-6 py-4 text-gray-500 font-medium">
                    {alum.telefono || "Sin Tlf"}
                  </td>

                  <td className="px-6 py-4">
                    <input 
                      type="text" 
                      placeholder="Nota opcional..."
                      className="w-full bg-gray-50 border border-gray-200 rounded-md px-3 py-2 text-sm focus:ring-1 focus:ring-blue-500 focus:border-blue-500 outline-none"
                      value={alum.observacion}
                      onChange={(e) => handleObservacion(alum.inscripcionId, e.target.value)}
                    />
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
