import { useEffect, useState } from "react";
import { useAuth } from "../hooks/useAuth";
import ChatMessages from "../components/ChatMessages";
import { userService } from "../services";

export default function MensagensPaciente() {
  const { user } = useAuth();
  const [medicos, setMedicos] = useState<Array<{ id: string; nome: string; role: string }>>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadMedicos();
  }, []);

  const loadMedicos = async () => {
    try {
      setLoading(true);
      console.log("[MensagensPaciente] Carregando médicos...");
      
      // Buscar todos os médicos disponíveis
      const medicosData = await userService.getAllUsers();
      const medicosFiltrados = medicosData
        .filter((u: any) => u.role === "medico")
        .map((m: any) => ({
          id: m.user_id || m.id,
          nome: m.nome || m.full_name || "Médico",
          role: "medico",
        }));

      console.log("[MensagensPaciente] Médicos carregados:", medicosFiltrados);
      setMedicos(medicosFiltrados);
    } catch (error) {
      console.error("[MensagensPaciente] Erro ao carregar médicos:", error);
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600 dark:text-gray-400">Carregando mensagens...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-7xl mx-auto">
      <div className="mb-6">
        <h1 className="text-3xl font-bold text-gray-900 dark:text-white">
          Mensagens
        </h1>
        <p className="text-gray-600 dark:text-gray-400 mt-2">
          Converse com seus médicos
        </p>
      </div>

      <div className="bg-white dark:bg-slate-800 rounded-lg shadow-sm border border-gray-200 dark:border-slate-700 overflow-hidden">
        <ChatMessages
          currentUserId={user?.id || ""}
          currentUserName={user?.nome}
          availableUsers={medicos}
        />
      </div>
    </div>
  );
}
