"use client";

import { useState, useRef, useEffect } from "react";
import { Send, UserCircle } from "lucide-react";
import { sendMessage, markChatRead } from "@/app/actions/chat";

export default function ChatClient({ conversaciones, currentUser }: { conversaciones: any[], currentUser: any }) {
  const [activeChatId, setActiveChatId] = useState<string | null>(conversaciones.length > 0 ? conversaciones[0].id : null);
  const [msgInput, setMsgInput] = useState("");
  const [isSending, setIsSending] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  const activeChat = conversaciones.find(c => c.id === activeChatId);

  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
    if (activeChatId) {
      markChatRead(activeChatId);
    }
  }, [activeChatId, conversaciones]);

  const handleSend = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!msgInput.trim() || !activeChatId) return;
    
    setIsSending(true);
    await sendMessage(activeChatId, msgInput.trim());
    setMsgInput("");
    setIsSending(false);
  };

  if (conversaciones.length === 0) {
    return (
      <div className="flex-1 flex flex-col items-center justify-center p-8 text-center bg-gray-50">
        <UserCircle className="w-16 h-16 text-gray-300 mb-4" />
        <h3 className="text-xl font-bold text-gray-600">Sin Mensajes</h3>
        <p className="text-gray-400 mt-2">No tienes conversaciones activas en este momento.</p>
      </div>
    );
  }

  return (
    <div className="flex h-full w-full">
      {/* Lista de Conversaciones */}
      <div className="w-1/3 min-w-[250px] border-r border-gray-100 flex flex-col bg-gray-50/50">
        <div className="p-4 border-b border-gray-100 bg-white">
          <h2 className="font-bold text-gray-700">Conversaciones</h2>
        </div>
        <div className="flex-1 overflow-y-auto p-2 space-y-1">
          {conversaciones.map(conv => {
            const isProfesor = currentUser.role === "PROFESOR";
            const chatName = isProfesor ? conv.colegio.nombre : conv.profesor.name || conv.profesor.email;
            
            const unreadCount = conv.mensajes.filter((m: any) => !m.read && m.senderId !== currentUser.id).length;
            
            return (
              <button
                key={conv.id}
                onClick={() => setActiveChatId(conv.id)}
                className={`w-full text-left p-3 rounded-xl transition-all flex items-center gap-3 ${
                  activeChatId === conv.id ? "bg-[#0066ff] text-white shadow-md" : "hover:bg-gray-100 text-gray-700"
                }`}
              >
                <div className="relative">
                  <UserCircle className={`w-10 h-10 ${activeChatId === conv.id ? "text-blue-200" : "text-gray-400"}`} />
                  {unreadCount > 0 && (
                    <span className="absolute -top-1 -right-1 bg-red-500 text-white text-[10px] font-bold w-4 h-4 rounded-full flex items-center justify-center">
                      {unreadCount}
                    </span>
                  )}
                </div>
                <div className="flex-1 min-w-0">
                  <div className="font-bold truncate text-sm">{chatName}</div>
                  <div className={`text-xs truncate ${activeChatId === conv.id ? "text-blue-100" : "text-gray-400"}`}>
                    {conv.asunto}
                  </div>
                </div>
              </button>
            );
          })}
        </div>
      </div>

      {/* Área de Chat */}
      <div className="flex-1 flex flex-col min-w-0 bg-gray-50">
        {activeChat ? (
          <>
            {/* Chat Header */}
            <div className="p-4 bg-white border-b border-gray-100 flex items-center justify-between shadow-sm z-10">
              <div className="flex items-center gap-3">
                <UserCircle className="w-10 h-10 text-gray-400" />
                <div>
                  <h3 className="font-bold text-gray-800">
                    {currentUser.role === "PROFESOR" ? activeChat.colegio.nombre : activeChat.profesor.name || activeChat.profesor.email}
                  </h3>
                  <p className="text-xs text-gray-500">Asunto: {activeChat.asunto}</p>
                </div>
              </div>
            </div>

            {/* Mensajes */}
            <div className="flex-1 overflow-y-auto p-4 space-y-4">
              {activeChat.mensajes.length === 0 ? (
                <div className="text-center text-gray-400 my-8 text-sm">
                  Envía un mensaje para comenzar la conversación.
                </div>
              ) : (
                activeChat.mensajes.map((m: any) => {
                  const isMine = m.senderId === currentUser.id;
                  return (
                    <div key={m.id} className={`flex ${isMine ? "justify-end" : "justify-start"}`}>
                      <div className={`max-w-[75%] rounded-2xl px-5 py-3 ${
                        isMine 
                          ? "bg-[#0066ff] text-white rounded-br-none shadow-sm" 
                          : "bg-white text-gray-700 border border-gray-100 rounded-bl-none shadow-sm"
                      }`}>
                        {!isMine && (
                          <div className="text-[10px] font-bold mb-1 opacity-50 uppercase">
                            {m.sender.name || "Usuario"}
                          </div>
                        )}
                        <p className="text-sm whitespace-pre-wrap leading-relaxed">{m.contenido}</p>
                        <div className={`text-[10px] mt-2 text-right ${isMine ? "text-blue-200" : "text-gray-400"}`}>
                          {new Date(m.createdAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                        </div>
                      </div>
                    </div>
                  );
                })
              )}
              <div ref={messagesEndRef} />
            </div>

            {/* Input form */}
            <div className="p-4 bg-white border-t border-gray-100">
              <form onSubmit={handleSend} className="flex gap-3">
                <input
                  type="text"
                  value={msgInput}
                  onChange={e => setMsgInput(e.target.value)}
                  placeholder="Escribe un mensaje..."
                  className="flex-1 bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition-all"
                  disabled={isSending}
                />
                <button
                  type="submit"
                  disabled={!msgInput.trim() || isSending}
                  className="bg-[#1e2a47] text-white rounded-xl px-6 font-bold flex items-center justify-center hover:bg-[#f04b50] transition-colors disabled:opacity-50"
                >
                  <Send className="w-5 h-5" />
                </button>
              </form>
            </div>
          </>
        ) : (
          <div className="flex-1 flex items-center justify-center text-gray-400">
            Selecciona una conversación para comenzar
          </div>
        )}
      </div>
    </div>
  );
}
