"use client";

import { useState } from "react";
import Link from "next/link";
import { LogOut, CheckCircle, Info, XCircle } from "lucide-react";
import { BookOpen, User } from "lucide-react";
import Script from "next/script";
import { solicitarInscripcion } from "@/app/actions/solicitarCurso";

type UserData = { id: string; name: string | null; email: string; telefono: string | null; status: string };
type MiCurso = { inscripcionId: string; cursoId: string; titulo: string; colegioNombre: string; fechaInicio: string | null; estadoFlujo: string; estadoPago: string };
type CursoDisponible = { id: string; titulo: string; colegioId: string; colegio: { nombre: string; requisitosInscripcion: string | null } };

export default function EstudianteLayoutClient({
  user, misCursos, cursosDisponibles
}: {
  user: UserData;
  misCursos: MiCurso[];
  cursosDisponibles: CursoDisponible[];
}) {
  const [modalOpen, setModalOpen] = useState(false);
  const [pagoModalOpen, setPagoModalOpen] = useState(false);
  const [selectedCurso, setSelectedCurso] = useState<CursoDisponible | null>(null);
  const [selectedPagoCurso, setSelectedPagoCurso] = useState<MiCurso | null>(null);
  const [observacion, setObservacion] = useState("");
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState("");

  const handleOpenModal = (curso: CursoDisponible) => {
    setSelectedCurso(curso);
    setObservacion("");
    setMessage("");
    setModalOpen(true);
  };

  const handleOpenPagoModal = (curso: MiCurso) => {
    setSelectedPagoCurso(curso);
    setMessage("");
    setPagoModalOpen(true);
  };

  const submitSolicitud = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedCurso) return;
    setLoading(true);
    setMessage("");

    const res = await solicitarInscripcion(selectedCurso.id, user.id, selectedCurso.colegioId, observacion);
    if (res.success) {
      setMessage("✅ Tu solicitud ha sido enviada con éxito.");
      setTimeout(() => {
        setModalOpen(false);
        window.location.reload(); // Recargar para actualizar los cursos
      }, 1500);
    } else {
      setMessage(`❌ Error: ${res.error}`);
    }
    setLoading(false);
  };

  return (
    <div className="min-h-screen bg-gray-50 flex flex-col">
      <Script src="https://upload-widget.cloudinary.com/global/all.js" strategy="lazyOnload" />
      {/* Header Estudiante */}
      <header className="bg-[#1e2a47] text-white px-8 py-6 shadow-md border-b-4 border-[#f04b50]">
        <div className="max-w-6xl mx-auto flex items-center justify-between">
          <div className="flex items-center gap-4">
            <div className="w-12 h-12 bg-white/10 rounded-full flex items-center justify-center">
              <User className="w-6 h-6 text-white" />
            </div>
            <div>
              <h1 className="text-xl font-extrabold tracking-tight">Portal del Estudiante</h1>
              <p className="text-gray-300 text-sm">{user.name || user.email}</p>
            </div>
          </div>
          <div className="flex items-center gap-4">
            <Link href="/perfil" className="flex items-center gap-2 hover:bg-white/10 px-4 py-2 rounded-lg text-sm font-semibold transition-colors border border-white/20">
              <User className="w-4 h-4" />
              Mi Perfil
            </Link>
            <Link href="/api/auth/signout" className="flex items-center gap-2 hover:bg-white/10 px-4 py-2 rounded-lg text-sm font-semibold transition-colors">
              <LogOut className="w-4 h-4" />
              Cerrar sesión
            </Link>
          </div>
        </div>
      </header>

      <main className="max-w-6xl mx-auto px-8 py-10 w-full grid grid-cols-1 gap-10">
        
        {/* Mis Cursos */}
        <section>
          <div className="flex items-center justify-between mb-6">
            <h2 className="text-2xl font-extrabold text-gray-800 flex items-center gap-2">
              <CheckCircle className="w-6 h-6 text-green-500" /> Mis Cursos Registrados
            </h2>
          </div>

          <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
            {misCursos.length === 0 ? (
              <div className="text-center text-gray-400 py-10">
                <BookOpen className="w-12 h-12 mx-auto mb-3 opacity-20" />
                <p>Aún no te has inscrito ni solicitado ningún curso.</p>
              </div>
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full text-left text-sm text-gray-500">
                  <thead className="bg-gray-50 text-gray-700 font-semibold uppercase text-xs">
                    <tr>
                      <th className="px-6 py-4 rounded-tl-lg">Curso</th>
                      <th className="px-6 py-4">Sede / Colegio</th>
                      <th className="px-6 py-4">Fase Inscripción</th>
                      <th className="px-6 py-4">Estado de Pago</th>
                      <th className="px-6 py-4 rounded-tr-lg text-right">Acciones</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-100">
                    {misCursos.map((c) => (
                      <tr key={c.inscripcionId} className="hover:bg-gray-50 transition-colors">
                        <td className="px-6 py-4 font-bold text-gray-800">{c.titulo}</td>
                        <td className="px-6 py-4 text-gray-600">{c.colegioNombre}</td>
                        <td className="px-6 py-4">
                          <span className={`px-3 py-1 text-xs font-bold rounded-full ${
                            c.estadoFlujo === "INSCRITO" ? "bg-green-100 text-green-700" :
                            c.estadoFlujo === "PENDIENTE_CONTACTAR" ? "bg-yellow-100 text-yellow-700" :
                            "bg-blue-100 text-blue-700"
                          }`}>
                            {c.estadoFlujo.replace(/_/g, " ")}
                          </span>
                        </td>
                        <td className="px-6 py-4 font-semibold text-gray-700">
                          {c.estadoPago}
                        </td>
                        <td className="px-6 py-4 text-right">
                          <button
                            onClick={() => handleOpenPagoModal(c)}
                            className="bg-blue-50 text-blue-600 hover:bg-blue-600 hover:text-white px-4 py-1.5 rounded-lg text-xs font-bold transition-colors"
                          >
                            Reportar Pago
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </section>

        {/* Cursos Disponibles */}
        <section>
          <div className="flex items-center justify-between mb-6">
            <h2 className="text-2xl font-extrabold text-gray-800 flex items-center gap-2">
              <Info className="w-6 h-6 text-[#0066ff]" /> Cursos Disponibles
            </h2>
          </div>

          {cursosDisponibles.length === 0 ? (
            <div className="bg-white rounded-2xl p-8 border border-gray-100 shadow-sm text-center text-gray-500">
              No hay más cursos disponibles por el momento.
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {cursosDisponibles.map((curso) => (
                <div key={curso.id} className="bg-white border border-gray-100 rounded-2xl shadow-sm hover:shadow-md transition-shadow overflow-hidden flex flex-col">
                  <div className="bg-[#1e2a47] p-5">
                    <h3 className="text-white font-extrabold text-lg leading-tight">{curso.titulo}</h3>
                  </div>
                  <div className="p-5 flex-1 flex flex-col justify-between gap-4">
                    <p className="text-sm font-semibold text-gray-600">🏛️ {curso.colegio.nombre}</p>
                    <button
                      onClick={() => handleOpenModal(curso)}
                      className="w-full bg-blue-50 hover:bg-[#0066ff] text-[#0066ff] hover:text-white font-bold py-2.5 rounded-xl text-sm transition-colors border border-blue-200"
                    >
                      Solicitar Inscripción
                    </button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </section>
      </main>

      {/* Modal / Popup Form */}
      {modalOpen && selectedCurso && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
          <div className="bg-white w-full max-w-lg rounded-2xl shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200">
            <form onSubmit={submitSolicitud} className="flex flex-col h-full">
              {/* Header Modal */}
              <div className="bg-[#1e2a47] px-6 py-4 flex items-center justify-between">
                <h3 className="text-white font-extrabold text-lg">Solicitar &quot;{selectedCurso.titulo}&quot;</h3>
                <button type="button" onClick={() => setModalOpen(false)} className="text-gray-400 hover:text-white transition-colors">
                  <XCircle className="w-6 h-6" />
                </button>
              </div>

              {/* Body Modal */}
              <div className="p-6 space-y-4">
                <p className="text-sm text-gray-600 font-medium">
                  Al enviar esta solicitud, la institución (<span className="font-bold text-gray-800">{selectedCurso.colegio.nombre}</span>) será notificada y te contactará para formalizar tu proceso.
                </p>

                {selectedCurso.colegio.requisitosInscripcion && (
                  <div className="bg-blue-50 border border-blue-100 p-4 rounded-xl text-sm">
                    <h4 className="font-bold text-blue-800 mb-1">📋 Requisitos de Inscripción:</h4>
                    <p className="text-blue-900 whitespace-pre-line leading-relaxed">{selectedCurso.colegio.requisitosInscripcion}</p>
                  </div>
                )}

                {message && (
                  <div className={`p-4 rounded-xl text-sm font-bold ${message.startsWith('✅') ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
                    {message}
                  </div>
                )}

                <div>
                  <label htmlFor="observacion" className="block text-sm font-bold text-gray-700 mb-2">
                    Observaciones / Mensaje adicional (Opcional)
                  </label>
                  <textarea
                    id="observacion"
                    rows={4}
                    value={observacion}
                    onChange={(e) => setObservacion(e.target.value)}
                    placeholder="Ej. Me gustaría saber si hay horarios de tarde..."
                    className="w-full bg-gray-50 border border-gray-200 rounded-xl p-4 text-sm text-gray-800 focus:outline-none focus:ring-2 focus:ring-[#0066ff] placeholder-gray-400 resize-none"
                  />
                </div>
              </div>

              {/* Footer Modal */}
              <div className="p-6 pt-0 border-t border-gray-100 mt-auto flex items-center justify-end gap-3 rounded-b-2xl bg-gray-50">
                <button
                  type="button"
                  onClick={() => setModalOpen(false)}
                  className="px-5 py-2.5 rounded-xl font-bold text-gray-500 hover:bg-gray-200 transition-colors text-sm"
                >
                  Cancelar
                </button>
                <button
                  type="submit"
                  disabled={loading}
                  className="bg-[#f04b50] hover:bg-red-600 text-white px-6 py-2.5 rounded-xl font-bold flex items-center justify-center gap-2 transition-colors disabled:opacity-50 text-sm shadow-md"
                >
                  {loading ? (
                    <span className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin"></span>
                  ) : "Enviar Solicitud"}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Modal Reporte de Pago */}
      {pagoModalOpen && selectedPagoCurso && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
          <div className="bg-white w-full max-w-lg rounded-2xl shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200">
            <ReportePagoForm curso={selectedPagoCurso} onClose={() => setPagoModalOpen(false)} />
          </div>
        </div>
      )}
    </div>
  );
}

function ReportePagoForm({ curso, onClose }: { curso: MiCurso; onClose: () => void }) {
  const [loading, setLoading] = useState(false);
  const [comprobanteFile, setComprobanteFile] = useState<File | null>(null);
  const [referencia, setReferencia] = useState("");
  const [monto, setMonto] = useState("");
  const [fechaPago, setFechaPago] = useState("");
  const [concepto, setConcepto] = useState("INSCRIPCION");
  const [message, setMessage] = useState("");

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!comprobanteFile) {
      setMessage("❌ Debes adjuntar el comprobante (imagen o PDF).");
      return;
    }
    setLoading(true);

    const formData = new FormData();
    formData.append("inscripcionId", curso.inscripcionId);
    formData.append("referencia", referencia);
    formData.append("monto", monto);
    formData.append("fechaPago", fechaPago);
    formData.append("concepto", concepto);
    formData.append("comprobante", comprobanteFile);

    try {
      const res = await fetch("/api/estudiante/reportar-pago", {
        method: "POST",
        body: formData // No Headers content-type is needed for FormData
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error);
      setMessage("✅ Pago reportado enviado.");
      setTimeout(() => {
        window.location.reload();
      }, 1500);
    } catch (err: any) {
      setMessage("❌ " + err.message);
      setLoading(false);
    }
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      setComprobanteFile(e.target.files[0]);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="flex flex-col h-full">
      <div className="bg-green-600 px-6 py-4 flex items-center justify-between">
        <h3 className="text-white font-extrabold text-lg">Reportar Pago - {curso.titulo}</h3>
        <button type="button" onClick={onClose} className="text-white/80 hover:text-white">
          <XCircle className="w-6 h-6" />
        </button>
      </div>
      <div className="p-6 space-y-4 max-h-[70vh] overflow-y-auto">
        {message && (
          <div className={`p-4 rounded-xl text-sm font-bold ${message.startsWith('✅') ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
            {message}
          </div>
        )}
        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-bold text-gray-700 mb-1">Concepto</label>
            <select value={concepto} onChange={e => setConcepto(e.target.value)} required
              className="w-full bg-gray-50 border border-gray-200 rounded-lg p-3 text-sm focus:ring-2 focus:ring-green-500 outline-none">
              <option value="INSCRIPCION">Inscripción / Formalización</option>
              <option value="MENSUALIDAD">Pago Mensualidad/Cuota</option>
              <option value="GUIA_MATERIAL">Material/Guía</option>
              <option value="CERTIFICADO">Certificado Impreso</option>
              <option value="OTRO">Otro</option>
            </select>
          </div>
          <div>
             <label className="block text-sm font-bold text-gray-700 mb-1">Monto Pagado (bs o $)</label>
             <input type="number" step="0.01" value={monto} onChange={e => setMonto(e.target.value)} placeholder="Ej: 10.00"
               className="w-full bg-gray-50 border border-gray-200 rounded-lg p-3 text-sm focus:ring-2 focus:ring-green-500 outline-none" />
          </div>
        </div>
        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-bold text-gray-700 mb-1">Referencia / Recibo</label>
            <input type="text" required value={referencia} onChange={e => setReferencia(e.target.value)} placeholder="Últimos 4-6 dígitos"
              className="w-full bg-gray-50 border border-gray-200 rounded-lg p-3 text-sm focus:ring-2 focus:ring-green-500 outline-none" />
          </div>
          <div>
             <label className="block text-sm font-bold text-gray-700 mb-1">Fecha de Transferencia</label>
             <input type="date" required value={fechaPago} onChange={e => setFechaPago(e.target.value)}
               className="w-full bg-gray-50 border border-gray-200 rounded-lg p-3 text-sm focus:ring-2 focus:ring-green-500 outline-none" />
          </div>
        </div>
        
        <div>
           <label className="block text-sm font-bold text-gray-700 mb-1">Capture del Comprobante (Obligatorio)</label>
           <input type="file" accept="image/*,.pdf" onChange={handleFileChange} required className="w-full bg-gray-50 border border-gray-200 rounded-lg p-2 focus:ring-2 focus:ring-green-500 outline-none file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-green-50 file:text-green-700" />
           {comprobanteFile && (
             <p className="mt-2 text-sm text-green-600 font-semibold">Archivo seleccionado: {comprobanteFile.name}</p>
           )}
        </div>
      </div>
      <div className="p-6 border-t border-gray-100 flex justify-end gap-3 rounded-b-2xl bg-gray-50 mt-auto">
        <button type="button" onClick={onClose} className="px-5 py-2.5 rounded-xl font-bold text-gray-500 hover:bg-gray-200 text-sm">Cancelar</button>
        <button type="submit" disabled={loading} className="bg-green-600 hover:bg-green-700 text-white px-6 py-2.5 rounded-xl font-bold transition-colors disabled:opacity-50 text-sm shadow-md">
          {loading ? "Enviando..." : "Enviar Reporte"}
        </button>
      </div>
    </form>
  )
}
