'use client';

import { useState, useEffect } from 'react';
import useSWR from 'swr';
import { useBodyScrollLock } from '@/lib/body-scroll-lock';
import ChatWindow from './ChatWindow';
import NewConversationModal from './NewConversationModal';
import GroupSettingsModal from './GroupSettingsModal';

interface User {
  id: string;
  email: string;
  name: string | null;
}

interface Participant {
  id: string;
  email: string;
  name: string | null;
}

interface LastMessage {
  id: string;
  content: string | null;
  senderId: string;
  senderName: string;
  createdAt: string;
  hasFiles: boolean;
}

interface Conversation {
  id: string;
  name: string | null;
  type: string;
  displayName: string;
  participants: Participant[];
  lastMessage: LastMessage | null;
  unreadCount: number;
  updatedAt: string;
  createdAt: string;
}

const fetcher = (url: string) => fetch(url).then((res) => res.json());

export default function Messagerie() {
  const [selectedConversation, setSelectedConversation] = useState<string | null>(null);
  const [showNewConversation, setShowNewConversation] = useState(false);
  const [showGroupSettings, setShowGroupSettings] = useState(false);
  const [showSidebar, setShowSidebar] = useState(false);
  useBodyScrollLock(showSidebar);

  const { data: conversations, error, mutate } = useSWR<Conversation[]>(
    '/api/conversations',
    fetcher,
    {
      refreshInterval: 2000, // Rafraîchir toutes les 2 secondes
    }
  );

  const selectedConv = conversations?.find((c) => c.id === selectedConversation);

  useEffect(() => {
    // Sélectionner automatiquement la première conversation si aucune n'est sélectionnée
    if (!selectedConversation && conversations && conversations.length > 0) {
      setSelectedConversation(conversations[0].id);
    }
  }, [conversations, selectedConversation]);

  const handleNewMessage = () => {
    // Rafraîchir la liste des conversations quand un nouveau message arrive
    mutate();
  };

  return (
    <div className="flex h-[calc(100vh-80px)] bg-white relative">
      {/* Overlay pour mobile */}
      {showSidebar && (
        <div
          className="fixed inset-0 bg-black/50 z-40 md:hidden"
          onClick={() => setShowSidebar(false)}
        />
      )}

      {/* Liste des conversations */}
      <div className={`absolute md:relative w-80 border-r border-gray-200 flex flex-col bg-white z-50 md:z-auto h-full transition-transform duration-300 ${
        showSidebar ? 'translate-x-0' : '-translate-x-full md:translate-x-0'
      }`}>
        <div className="p-4 border-b border-gray-200 flex items-center justify-between">
          <h2 className="text-lg font-semibold text-gray-900">Messages</h2>
          <div className="flex items-center gap-2">
            <button
              onClick={() => setShowNewConversation(true)}
              className="p-2 rounded-lg bg-lblue text-white hover:bg-dblue transition-colors"
              title="Nouvelle conversation"
            >
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
              </svg>
            </button>
            <button
              onClick={() => setShowSidebar(false)}
              className="p-2 rounded-lg hover:bg-gray-100 transition-colors md:hidden"
              title="Fermer"
            >
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>
        </div>

        <div className="flex-1 overflow-y-auto">
          {error && (
            <div className="p-4 text-sm text-red-600">
              Erreur lors du chargement des conversations
            </div>
          )}
          {!conversations && !error && (
            <div className="p-4 text-sm text-gray-500 text-center">Chargement...</div>
          )}
          {conversations && conversations.length === 0 && (
            <div className="p-4 text-sm text-gray-500 text-center">
              Aucune conversation. Créez-en une nouvelle !
            </div>
          )}
          {conversations && conversations.length > 0 && (
            <div className="divide-y divide-gray-100">
              {conversations.map((conversation) => (
                <button
                  key={conversation.id}
                  onClick={() => {
                    setSelectedConversation(conversation.id);
                    setShowSidebar(false); // Fermer la sidebar sur mobile après sélection
                    if (conversation.type === 'group') {
                      setShowGroupSettings(false);
                    }
                  }}
                  className={`w-full p-4 text-left hover:bg-gray-50 transition-colors ${
                    selectedConversation === conversation.id ? 'bg-lblue/10' : ''
                  }`}
                >
                  <div className="flex items-start gap-3">
                    <div className="w-12 h-12 rounded-full bg-gradient-to-br from-lblue to-dblue flex items-center justify-center flex-shrink-0">
                      <span className="text-white font-semibold text-sm">
                        {conversation.type === 'group'
                          ? conversation.displayName.charAt(0).toUpperCase()
                          : conversation.displayName
                              .split(' ')
                              .map((n) => n.charAt(0))
                              .join('')
                              .toUpperCase()
                              .slice(0, 2)}
                      </span>
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center justify-between mb-1">
                        <div className="flex items-center gap-2 flex-1 min-w-0">
                          <h3 className="text-sm font-semibold text-gray-900 truncate">
                            {conversation.displayName}
                          </h3>
                          {conversation.unreadCount > 0 && (
                            <span className="flex-shrink-0 w-5 h-5 bg-red-500 text-white text-xs font-semibold rounded-full flex items-center justify-center">
                              {conversation.unreadCount > 99 ? '99+' : conversation.unreadCount}
                            </span>
                          )}
                        </div>
                        {conversation.lastMessage && (
                          <span className="text-xs text-gray-500 flex-shrink-0 ml-2">
                            {new Date(conversation.lastMessage.createdAt).toLocaleTimeString('fr-FR', {
                              hour: '2-digit',
                              minute: '2-digit',
                            })}
                          </span>
                        )}
                      </div>
                      {conversation.lastMessage ? (
                        <p className="text-xs md:text-sm text-gray-600 truncate">
                          {conversation.type === 'group' && conversation.lastMessage.senderName
                            ? `${conversation.lastMessage.senderName}: `
                            : ''}
                          {conversation.lastMessage.hasFiles && !conversation.lastMessage.content
                            ? '📎 Fichier'
                            : conversation.lastMessage.content || '📎 Fichier'}
                        </p>
                      ) : (
                        <p className="text-xs md:text-sm text-gray-400 italic">Aucun message</p>
                      )}
                    </div>
                  </div>
                </button>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Fenêtre de chat */}
      <div className="flex-1 flex flex-col w-full">
        {selectedConversation && selectedConv ? (
          <ChatWindow
            conversationId={selectedConversation}
            conversation={selectedConv}
            onNewMessage={handleNewMessage}
            onShowGroupSettings={() => setShowGroupSettings(true)}
            onShowSidebar={() => setShowSidebar(true)}
          />
        ) : (
          <div className="flex-1 flex items-center justify-center bg-gray-50">
            <div className="text-center p-4">
              <svg
                className="w-16 h-16 text-gray-400 mx-auto mb-4"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"
                />
              </svg>
              <p className="text-gray-500 mb-4">Sélectionnez une conversation pour commencer</p>
              <button
                onClick={() => setShowSidebar(true)}
                className="md:hidden px-4 py-2 bg-lblue text-white rounded-lg hover:bg-dblue transition-colors"
              >
                Voir les conversations
              </button>
            </div>
          </div>
        )}
      </div>

      {/* Modales */}
      {showNewConversation && (
        <NewConversationModal
          onClose={() => setShowNewConversation(false)}
          onConversationCreated={(conversationId) => {
            setSelectedConversation(conversationId);
            setShowNewConversation(false);
            mutate();
          }}
        />
      )}

      {showGroupSettings && selectedConv && selectedConv.type === 'group' && (
        <GroupSettingsModal
          conversation={selectedConv}
          onClose={() => setShowGroupSettings(false)}
          onUpdate={mutate}
        />
      )}
    </div>
  );
}
