import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { ArrowLeft, Mail, MailOpen, Trash2, Search } from "lucide-react";
import toast from "react-hot-toast";
import { useAuth } from "../hooks/useAuth";
import { messageService, doctorService } from "../services";
import type { Message } from "../services";
import { format } from "date-fns";
import { ptBR } from "date-fns/locale";
import ChatMessages from "../components/ChatMessages";

export default function MensagensMedico() {
  const { user } = useAuth();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [messages, setMessages] = useState<Message[]>([]);
  const [selectedMessage, setSelectedMessage] = useState<Message | null>(null);
  const [filter, setFilter] = useState<"all" | "unread" | "read">("all");
  const [searchTerm, setSearchTerm] = useState("");
  const [medicos, setMedicos] = useState<Array<{ id: string; nome: string; role: string }>>([]);

  // ============ VERSÃO ATUALIZADA - CACHE LIMPO ============
  // Verificar se é paciente
  const isPaciente = user && (user.role === "paciente" || user.role === "user");

  useEffect(() => {
    console.log("========================================");
    console.log("[MensagensMedico] 🔥 CÓDIGO NOVO CARREGADO!");
    console.log("[MensagensMedico] User:", user);
    console.log("[MensagensMedico] isPaciente:", isPaciente);
    console.log("[MensagensMedico] user.role:", user?.role);
    console.log("========================================");
    
    if (isPaciente) {
      console.log("[MensagensMedico] Carregando médicos para paciente");
      loadMedicos();
    } else if (user?.id) {
      console.log("[MensagensMedico] Carregando mensagens para médico");
      loadMessages();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [user?.id, filter, isPaciente]);

  const loadMedicos = async () => {
    try {
      setLoading(true);
      console.log("[Mensagens] Carregando lista de médicos...");
      const medicosData = await doctorService.list();
      console.log("[Mensagens] Médicos encontrados:", medicosData);
      
      const medicosFiltrados = medicosData.map((m: any) => ({
        id: m.user_id || m.id,
        nome: m.full_name || m.nome || "Médico",
        role: "medico",
      }));
      
      console.log("[Mensagens] Médicos filtrados:", medicosFiltrados);
      setMedicos(medicosFiltrados);
    } catch (error) {
      console.error("[Mensagens] Erro ao carregar médicos:", error);
      toast.error("Erro ao carregar lista de médicos");
    } finally {
      setLoading(false);
    }
  };

  const loadMessages = async () => {
    if (!user?.id) return;

    try {
      setLoading(true);
      console.log("[MensagensMedico] Carregando mensagens...");

      let fetchedMessages: Message[] = [];

      if (filter === "unread") {
        fetchedMessages = await messageService.getUnreadMessages(user.id);
      } else if (filter === "read") {
        const allMessages = await messageService.getReceivedMessages(user.id);
        fetchedMessages = allMessages.filter((m) => m.read);
      } else {
        fetchedMessages = await messageService.getReceivedMessages(user.id);
      }

      console.log(
        "[MensagensMedico] Mensagens carregadas:",
        fetchedMessages.length
      );
      setMessages(fetchedMessages);
    } catch (error) {
      console.error("[MensagensMedico] Erro ao carregar mensagens:", error);
      toast.error("Erro ao carregar mensagens");
    } finally {
      setLoading(false);
    }
  };

  const handleSelectMessage = async (message: Message) => {
    setSelectedMessage(message);

    // Marcar como lida se não estiver lida
    if (!message.read) {
      try {
        await messageService.markAsRead(message.id);
        // Atualizar localmente
        setMessages((prev) =>
          prev.map((m) => (m.id === message.id ? { ...m, read: true } : m))
        );
      } catch (error) {
        console.error("[MensagensMedico] Erro ao marcar como lida:", error);
      }
    }
  };

  const handleDeleteMessage = async (messageId: string) => {
    if (!confirm("Deseja realmente excluir esta mensagem?")) return;

    try {
      await messageService.delete(messageId);
      toast.success("Mensagem excluída com sucesso!");
      setMessages((prev) => prev.filter((m) => m.id !== messageId));
      if (selectedMessage?.id === messageId) {
        setSelectedMessage(null);
      }
    } catch (error) {
      console.error("[MensagensMedico] Erro ao excluir mensagem:", error);
      toast.error("Erro ao excluir mensagem");
    }
  };

  const handleToggleRead = async (message: Message) => {
    try {
      if (message.read) {
        await messageService.markAsUnread(message.id);
        toast.success("Marcada como não lida");
      } else {
        await messageService.markAsRead(message.id);
        toast.success("Marcada como lida");
      }
      // Atualizar localmente
      setMessages((prev) =>
        prev.map((m) => (m.id === message.id ? { ...m, read: !m.read } : m))
      );
      if (selectedMessage?.id === message.id) {
        setSelectedMessage({ ...selectedMessage, read: !selectedMessage.read });
      }
    } catch (error) {
      console.error("[MensagensMedico] Erro ao alterar status:", error);
      toast.error("Erro ao alterar status da mensagem");
    }
  };

  const filteredMessages = messages.filter((message) => {
    const matchesSearch =
      message.subject?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      message.content?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      message.sender_name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      message.sender_email?.toLowerCase().includes(searchTerm.toLowerCase());
    return matchesSearch;
  });

  const unreadCount = messages.filter((m) => !m.read).length;

  // Se for paciente, mostrar interface de chat com médicos
  if (isPaciente) {
    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 px-4">
        {/* ✅ BANNER DE CONFIRMAÇÃO - CÓDIGO NOVO CARREGADO ✅ */}
        <div className="mb-4 p-4 bg-green-100 dark:bg-green-900 border-2 border-green-600 rounded-lg">
          <p className="text-green-800 dark:text-green-100 font-bold text-center text-xl">
            ✅ INTERFACE DE PACIENTE ATIVA - Código Atualizado Carregado
          </p>
        </div>

        <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" style={{ minHeight: '600px' }}>
          <ChatMessages
            currentUserId={user?.id || ""}
            currentUserName={user?.nome}
            availableUsers={medicos}
          />
        </div>
      </div>
    );
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="w-16 h-16 border-4 border-green-600 border-t-transparent rounded-full animate-spin" />
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 py-4 sm:py-6 lg:py-8 px-4 sm:px-6">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="flex items-center justify-between mb-6">
          <div>
            <h1 className="text-2xl lg:text-3xl font-bold text-gray-900">
              Mensagens
            </h1>
            <p className="text-sm text-gray-600 mt-1">
              {unreadCount > 0
                ? `${unreadCount} ${
                    unreadCount > 1
                      ? "mensagens não lidas"
                      : "mensagem não lida"
                  }`
                : "Nenhuma mensagem não lida"}
            </p>
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Lista de mensagens */}
          <div className="lg:col-span-1 bg-white rounded-lg shadow">
            <div className="p-4 border-b border-gray-200">
              {/* Filtros */}
              <div className="flex gap-2 mb-4">
                <button
                  onClick={() => setFilter("all")}
                  className={`flex-1 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${
                    filter === "all"
                      ? "bg-green-600 text-white"
                      : "bg-gray-100 text-gray-700 hover:bg-gray-200"
                  }`}
                >
                  Todas ({messages.length})
                </button>
                <button
                  onClick={() => setFilter("unread")}
                  className={`flex-1 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${
                    filter === "unread"
                      ? "bg-green-600 text-white"
                      : "bg-gray-100 text-gray-700 hover:bg-gray-200"
                  }`}
                >
                  Não lidas ({unreadCount})
                </button>
              </div>

              {/* Busca */}
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
                <input
                  type="text"
                  placeholder="Buscar mensagens..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent text-sm"
                />
              </div>
            </div>

            {/* Lista */}
            <div className="divide-y divide-gray-200 max-h-[600px] overflow-y-auto">
              {filteredMessages.length === 0 ? (
                <div className="p-8 text-center text-gray-500">
                  <Mail className="w-12 h-12 mx-auto mb-3 text-gray-300" />
                  <p className="text-sm">Nenhuma mensagem encontrada</p>
                </div>
              ) : (
                filteredMessages.map((message) => (
                  <div
                    key={message.id}
                    onClick={() => handleSelectMessage(message)}
                    className={`p-4 cursor-pointer hover:bg-gray-50 transition-colors ${
                      selectedMessage?.id === message.id ? "bg-green-50" : ""
                    } ${!message.read ? "bg-blue-50 hover:bg-blue-100" : ""}`}
                  >
                    <div className="flex items-start justify-between gap-2">
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2">
                          {!message.read ? (
                            <Mail className="w-4 h-4 text-blue-600 flex-shrink-0" />
                          ) : (
                            <MailOpen className="w-4 h-4 text-gray-400 flex-shrink-0" />
                          )}
                          <p
                            className={`text-sm truncate ${
                              !message.read
                                ? "font-semibold text-gray-900"
                                : "font-medium text-gray-700"
                            }`}
                          >
                            {message.sender_name ||
                              message.sender_email ||
                              "Paciente"}
                          </p>
                        </div>
                        <p
                          className={`text-sm mt-1 truncate ${
                            !message.read
                              ? "font-medium text-gray-900"
                              : "text-gray-600"
                          }`}
                        >
                          {message.subject}
                        </p>
                        <p className="text-xs text-gray-500 mt-1 line-clamp-2">
                          {message.content}
                        </p>
                        <p className="text-xs text-gray-400 mt-2">
                          {format(
                            new Date(message.created_at || Date.now()),
                            "dd/MM/yyyy 'às' HH:mm",
                            {
                              locale: ptBR,
                            }
                          )}
                        </p>
                      </div>
                    </div>
                  </div>
                ))
              )}
            </div>
          </div>

          {/* Visualização da mensagem */}
          <div className="lg:col-span-2 bg-white rounded-lg shadow">
            {selectedMessage ? (
              <div className="h-full flex flex-col">
                {/* Header da mensagem */}
                <div className="p-6 border-b border-gray-200">
                  <div className="flex items-start justify-between gap-4">
                    <div className="flex-1">
                      <h2 className="text-xl font-semibold text-gray-900 mb-2">
                        {selectedMessage.subject}
                      </h2>
                      <div className="flex items-center gap-2 text-sm text-gray-600">
                        <span className="font-medium">De:</span>
                        <span>
                          {selectedMessage.sender_name ||
                            selectedMessage.sender_email ||
                            "Paciente"}
                        </span>
                      </div>
                      <p className="text-xs text-gray-400 mt-1">
                        {format(
                          new Date(selectedMessage.created_at || Date.now()),
                          "dd 'de' MMMM 'de' yyyy 'às' HH:mm",
                          { locale: ptBR }
                        )}
                      </p>
                    </div>
                    <div className="flex gap-2">
                      <button
                        onClick={() => handleToggleRead(selectedMessage)}
                        className="p-2 text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded-lg transition-colors"
                        title={
                          selectedMessage.read
                            ? "Marcar como não lida"
                            : "Marcar como lida"
                        }
                      >
                        {selectedMessage.read ? (
                          <Mail className="w-5 h-5" />
                        ) : (
                          <MailOpen className="w-5 h-5" />
                        )}
                      </button>
                      <button
                        onClick={() => handleDeleteMessage(selectedMessage.id)}
                        className="p-2 text-red-600 hover:text-red-700 hover:bg-red-50 rounded-lg transition-colors"
                        title="Excluir mensagem"
                      >
                        <Trash2 className="w-5 h-5" />
                      </button>
                    </div>
                  </div>
                </div>

                {/* Conteúdo da mensagem */}
                <div className="flex-1 p-6 overflow-y-auto">
                  <div className="prose prose-sm max-w-none">
                    <p className="text-gray-700 whitespace-pre-wrap">
                      {selectedMessage.content}
                    </p>
                  </div>
                </div>
              </div>
            ) : (
              <div className="h-full flex items-center justify-center p-8">
                <div className="text-center text-gray-400">
                  <Mail className="w-16 h-16 mx-auto mb-4" />
                  <p className="text-lg font-medium">Selecione uma mensagem</p>
                  <p className="text-sm mt-2">
                    Clique em uma mensagem da lista para visualizar
                  </p>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
