"use client";

import { useState, useEffect, useRef } from "react";
import Link from "next/link";
import { BookOpen, Users, User, Clock, MapPin, MessageSquare, Send, XCircle, CheckCircle2 } from "lucide-react";
import { sendMessage, markChatRead, createConversacion } from "@/app/actions/chat";

export default function ProfesorLayoutClient({
  user, cursos, colegioDestino, conversacion
}: any) {
  const [chatOpen, setChatOpen] = useState(false);
  const [message, setMessage] = useState("");
  const [convId, setConvId] = useState<string | null>(conversacion?.id || null);
  const [mensajes, setMensajes] = useState<any[]>(conversacion?.mensajes || []);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // Scroll into view on messages change
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  useEffect(() => { if (chatOpen) scrollToBottom(); }, [chatOpen, mensajes]);

  // Handle Mark as Read when opening the chat
  useEffect(() => {
    if (chatOpen && convId) {
      markChatRead(convId);
    }
  }, [chatOpen, convId, user.id]);

  const handleSend = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!message.trim() || !colegioDestino) return;
    
    // Ensure we have a conversation initialized
    let tgtConv = convId;
    if (!tgtConv) {
      const ensured = await createConversacion(user.id, colegioDestino.id);
      if (ensured.success && ensured.conversacionId) {
        tgtConv = ensured.conversacionId;
        setConvId(tgtConv);
      }
    }

    // Send
    const tempMsg = { id: Date.now().toString(), contenido: message, senderId: user.id, createdAt: new Date() };
    setMensajes((prev) => [...prev, tempMsg]);
    const input = message;
    setMessage("");

    if (tgtConv) {
      await sendMessage(tgtConv, input);
    }
    // Replace with actual from db if needed (but we simulate the optimistic update)
  };

  const unreadCount = conversacion?.mensajes?.filter((m: any) => m.senderId !== user.id && !m.read).length || 0;

  return (
    <div className="min-h-screen bg-gray-50 flex flex-col relative">
      <header className="bg-[#1e2a47] text-white px-8 py-6 shadow-lg">
        <div className="max-w-6xl mx-auto flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-extrabold">Panel del Instructor</h1>
            <p className="text-gray-300 text-sm mt-1">Bienvenido, {user.name || user.email}</p>
          </div>
          <div className="flex items-center gap-4">
            <Link href="/perfil" className="flex items-center gap-2 hover:bg-white/20 bg-white/10 px-4 py-2 rounded-lg text-sm font-semibold transition-colors">
              <User className="w-4 h-4" />
              Mi Perfil
            </Link>
            <Link href="/api/auth/signout" className="bg-white/10 hover:bg-white/20 px-4 py-2 rounded-lg text-sm font-semibold transition-colors">
              Cerrar sesión
            </Link>
          </div>
        </div>
      </header>

      <main className="max-w-6xl mx-auto px-8 py-10 space-y-10 w-full flex-1">
        {/* Datos personales */}
        <section className="bg-white rounded-2xl shadow-sm border border-gray-100 p-8">
          <h2 className="text-xl font-extrabold text-gray-800 mb-6 flex items-center gap-2">
            <User className="w-5 h-5 text-[#0066ff]" /> Mis Datos
          </h2>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6 text-sm">
            <InfoCard label="Nombre" value={user.name || "—"} />
            <InfoCard label="Email" value={user.email} />
            <InfoCard label="Teléfono" value={user.telefono || "No registrado"} />
            <InfoCard label="Dirección" value={user.direccion || "No registrada"} />
            <InfoCard label="Estado" value={user.status === "SOLVENTE" || user.status === "ACTIVO" ? "✅ Activo" : "❌ Inactivo"} />
            <InfoCard label="Colegio Asignado" value={colegioDestino ? colegioDestino.nombre : "Global"} />
          </div>
        </section>

        {/* Cursos */}
        <section>
          <h2 className="text-xl font-extrabold text-gray-800 mb-6 flex items-center gap-2">
            <BookOpen className="w-5 h-5 text-[#f04b50]" /> Mis Cursos Asignados ({cursos.length})
          </h2>

          {cursos.length === 0 ? (
            <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-12 text-center text-gray-400">
              <BookOpen className="w-12 h-12 mx-auto mb-3 text-gray-200" />
              No tienes cursos asignados.
            </div>
          ) : (
            <div className="space-y-6">
              {cursos.map((c: any) => (
                <div key={c.id} className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
                  <div className="bg-gradient-to-r from-[#1e2a47] to-[#2d3f6b] px-8 py-5 text-white">
                    <div className="flex justify-between items-start">
                      <div>
                        <h3 className="text-lg font-extrabold">{c.titulo}</h3>
                        <p className="flex items-center gap-1 text-sm text-gray-300 mt-1">
                          <MapPin className="w-3.5 h-3.5" /> {c.colegio.nombre} | {c.horaEntrada} - {c.horaSalida}
                        </p>
                      </div>
                      <div className="text-right">
                        <span className="bg-white/20 px-3 py-1 rounded-full text-xs font-bold">{c.categoria}</span>
                      </div>
                    </div>
                  </div>
                  <div className="px-8 py-5">
                    <h4 className="text-sm font-bold text-gray-600 uppercase tracking-wider mb-3">Clases (Asistencia)</h4>
                    {c.clases && c.clases.length > 0 ? (
                      <div className="flex flex-wrap gap-3 mb-6">
                        {c.clases.map((clase: any) => (
                           <Link 
                              key={clase.id} 
                              href={`/profesor/clase/${clase.id}/asistencia`}
                              className="bg-gray-50 hover:bg-blue-50 border border-gray-200 hover:border-blue-300 text-gray-700 hover:text-[#0066ff] px-4 py-2 rounded-lg text-sm font-bold flex items-center gap-2 transition-colors shadow-sm"
                           >
                             <CheckCircle2 className="w-4 h-4" />
                             Clase {clase.numero}: {clase.titulo}
                           </Link>
                        ))}
                      </div>
                    ) : (
                      <p className="text-gray-400 text-sm mb-6">No hay clases registradas en este curso.</p>
                    )}

                    <h4 className="text-sm font-bold text-gray-600 uppercase tracking-wider mb-3">Matrícula ({c.inscripciones.length})</h4>
                    {c.inscripciones.length === 0 ? (
                      <p className="text-gray-400 text-sm">Sin inscritos.</p>
                    ) : (
                      <div className="overflow-x-auto">
                        <table className="w-full text-left text-sm text-gray-600">
                          <thead className="bg-gray-50 uppercase text-xs">
                            <tr>
                              <th className="px-4 py-3">Nombre</th>
                              <th className="px-4 py-3">Teléfono</th>
                              <th className="px-4 py-3">Estado</th>
                            </tr>
                          </thead>
                          <tbody>
                            {c.inscripciones.map((ins: any) => (
                              <tr key={ins.id} className="border-t border-gray-100 hover:bg-gray-50">
                                <td className="px-4 py-3 font-semibold text-gray-800">{ins.user.name}</td>
                                <td className="px-4 py-3">{ins.user.telefono || "—"}</td>
                                <td className="px-4 py-3">{ins.user.status === "SOLVENTE" ? "✅ Solvente" : "❌ Moroso"}</td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    )}
                  </div>
                </div>
              ))}
            </div>
          )}
        </section>
      </main>

      {/* Floating Chat Button */}
      {colegioDestino && (
        <button
          onClick={() => setChatOpen(!chatOpen)}
          className="fixed bottom-6 right-6 w-16 h-16 bg-[#0066ff] hover:bg-blue-600 text-white rounded-full shadow-2xl flex items-center justify-center transition-transform hover:scale-105"
        >
          {unreadCount > 0 && !chatOpen && (
            <span className="absolute -top-2 -right-2 bg-red-500 text-white text-[10px] font-bold px-2 py-0.5 rounded-full border-2 border-white">
              {unreadCount}
            </span>
          )}
          <MessageSquare className="w-7 h-7" />
        </button>
      )}

      {/* Chat Window */}
      {chatOpen && colegioDestino && (
        <div className="fixed bottom-24 right-6 w-96 bg-white rounded-2xl shadow-2xl border border-gray-200 overflow-hidden flex flex-col z-50 transition-all">
          <div className="bg-[#1e2a47] text-white p-4 flex items-center justify-between">
            <div>
              <h4 className="font-extrabold flex items-center gap-2">
                <MessageSquare className="w-4 h-4" /> Notificaciones
              </h4>
              <p className="text-xs text-blue-200">{colegioDestino.nombre}</p>
            </div>
            <button onClick={() => setChatOpen(false)} className="text-gray-300 hover:text-white transition-colors">
              <XCircle className="w-6 h-6" />
            </button>
          </div>
          <div className="h-80 overflow-y-auto p-4 bg-gray-50 space-y-4">
            {mensajes.length === 0 ? (
              <p className="text-center text-xs text-gray-400 mt-10">Sin mensajes aún. Inicia la comunicación.</p>
            ) : (
              mensajes.map((m: any, i: number) => {
                const soyYo = m.senderId === user.id;
                return (
                  <div key={i} className={`flex flex-col ${soyYo ? 'items-end' : 'items-start'}`}>
                    <div className={`px-4 py-2.5 rounded-2xl max-w-[85%] text-sm shadow-sm ${soyYo ? 'bg-[#0066ff] text-white rounded-br-none' : 'bg-white text-gray-800 border border-gray-200 rounded-bl-none'}`}>
                      {m.contenido}
                    </div>
                    <div className="flex items-center gap-1 mt-1 text-[10px] text-gray-400">
                      {new Date(m.createdAt).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}
                      {soyYo && (
                        <CheckCircle2 className={`w-3 h-3 ${m.read ? 'text-[#0066ff]' : 'text-gray-300'}`} />
                      )}
                    </div>
                  </div>
                );
              })
            )}
            <div ref={messagesEndRef} />
          </div>
          <form onSubmit={handleSend} className="p-3 border-t border-gray-100 flex gap-2 w-full bg-white">
            <input 
              type="text" 
              value={message}
              onChange={(e) => setMessage(e.target.value)}
              placeholder="Escribe un mensaje..."
              className="flex-1 text-sm px-4 py-2 bg-gray-50 border border-gray-200 rounded-full focus:outline-none focus:ring-1 focus:ring-[#0066ff]"
            />
            <button type="submit" className="w-10 h-10 bg-[#f04b50] hover:bg-red-600 text-white rounded-full flex items-center justify-center transition-colors">
              <Send className="w-4 h-4 ml-0.5" />
            </button>
          </form>
        </div>
      )}
    </div>
  );
}

function InfoCard({ label, value }: { label: string; value: string }) {
  return (
    <div className="bg-gray-50 border border-gray-100 rounded-xl p-4">
      <div className="text-xs text-gray-400 font-bold uppercase tracking-wider mb-1">{label}</div>
      <div className="text-gray-800 font-semibold">{value}</div>
    </div>
  );
}
