'use client';

import { useState, useEffect } from 'react';
import useSWR from 'swr';
import AlertModal from './AlertModal';

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

interface NewConversationModalProps {
  onClose: () => void;
  onConversationCreated: (conversationId: string) => void;
}

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

export default function NewConversationModal({
  onClose,
  onConversationCreated,
}: NewConversationModalProps) {
  const [search, setSearch] = useState('');
  const [selectedUsers, setSelectedUsers] = useState<string[]>([]);
  const [conversationType, setConversationType] = useState<'direct' | 'group'>('direct');
  const [groupName, setGroupName] = useState('');
  const [isCreating, setIsCreating] = useState(false);
  const [alertModal, setAlertModal] = useState<{
    show: boolean;
    type: 'success' | 'error' | 'info' | 'warning';
    title: string;
    message: string;
  } | null>(null);

  // Récupérer l'utilisateur actuel
  const { data: currentUser } = useSWR<User>('/api/auth/me', fetcher);

  const { data: users, error } = useSWR<User[]>(
    search ? `/api/users?search=${encodeURIComponent(search)}` : '/api/users',
    fetcher
  );

  // Filtrer l'utilisateur actuel de la liste des utilisateurs
  const availableUsers = users?.filter((user) => user.id !== currentUser?.id) || [];

  const handleUserToggle = (userId: string) => {
    if (selectedUsers.includes(userId)) {
      setSelectedUsers(selectedUsers.filter((id) => id !== userId));
    } else {
      setSelectedUsers([...selectedUsers, userId]);
    }
  };

  const handleCreate = async () => {
    if (selectedUsers.length === 0) {
      setAlertModal({
        show: true,
        type: 'warning',
        title: 'Sélection requise',
        message: 'Veuillez sélectionner au moins un utilisateur',
      });
      return;
    }

    if (conversationType === 'group' && !groupName.trim()) {
      setAlertModal({
        show: true,
        type: 'warning',
        title: 'Nom requis',
        message: 'Veuillez entrer un nom pour le groupe',
      });
      return;
    }

    setIsCreating(true);
    try {
      const response = await fetch('/api/conversations', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          participantIds: selectedUsers,
          type: conversationType,
          name: conversationType === 'group' ? groupName : null,
        }),
      });

      if (response.ok) {
        const conversation = await response.json();
        onConversationCreated(conversation.id);
      } else {
        const error = await response.json();
        setAlertModal({
          show: true,
          type: 'error',
          title: 'Erreur',
          message: error.error || 'Erreur lors de la création de la conversation',
        });
      }
    } catch (error) {
      console.error('Erreur:', error);
      setAlertModal({
        show: true,
        type: 'error',
        title: 'Erreur',
        message: 'Erreur lors de la création de la conversation',
      });
    } finally {
      setIsCreating(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-0 md:p-4">
      <div className="bg-white rounded-none md:rounded-lg shadow-xl w-full h-full md:h-auto md:max-w-md md:mx-4 md:max-h-[90vh] flex flex-col">
        <div className="p-4 md:p-6 border-b border-gray-200 flex-shrink-0">
          <div className="flex items-center justify-between">
            <h2 className="text-lg md:text-xl font-semibold text-gray-900">Nouvelle conversation</h2>
            <button
              onClick={onClose}
              className="text-gray-400 hover:text-gray-600 transition-colors"
            >
              <svg className="w-5 h-5 md:w-6 md:h-6" 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 p-4 md:p-6 space-y-4">
          {/* Type de conversation */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Type de conversation
            </label>
            <div className="flex gap-4">
              <label className="flex items-center">
                <input
                  type="radio"
                  value="direct"
                  checked={conversationType === 'direct'}
                  onChange={(e) => {
                    setConversationType(e.target.value as 'direct');
                    setGroupName('');
                  }}
                  className="mr-2"
                />
                <span className="text-sm text-gray-700">Directe</span>
              </label>
              <label className="flex items-center">
                <input
                  type="radio"
                  value="group"
                  checked={conversationType === 'group'}
                  onChange={(e) => setConversationType(e.target.value as 'group')}
                  className="mr-2"
                />
                <span className="text-sm text-gray-700">Groupe</span>
              </label>
            </div>
          </div>

          {/* Nom du groupe */}
          {conversationType === 'group' && (
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Nom du groupe
              </label>
              <input
                type="text"
                value={groupName}
                onChange={(e) => setGroupName(e.target.value)}
                placeholder="Entrez le nom du groupe"
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-lblue focus:border-transparent"
              />
            </div>
          )}

          {/* Recherche d'utilisateurs */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Rechercher des utilisateurs
            </label>
            <input
              type="text"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="Rechercher par nom ou email..."
              className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-lblue focus:border-transparent"
            />
          </div>

          {/* Liste des utilisateurs */}
          <div className="max-h-48 md:max-h-64 overflow-y-auto border border-gray-200 rounded-lg">
            {error && (
              <div className="p-3 md:p-4 text-sm text-red-600">
                Erreur lors du chargement des utilisateurs
              </div>
            )}
            {!users && !error && (
              <div className="p-3 md:p-4 text-sm text-gray-500 text-center">Chargement...</div>
            )}
            {availableUsers.length === 0 && users && (
              <div className="p-3 md:p-4 text-sm text-gray-500 text-center">Aucun utilisateur trouvé</div>
            )}
            {availableUsers.length > 0 && (
              <div className="divide-y divide-gray-100">
                {availableUsers.map((user) => (
                  <label
                    key={user.id}
                    className="flex items-center gap-2 md:gap-3 p-2 md:p-3 hover:bg-gray-50 cursor-pointer"
                  >
                    <input
                      type="checkbox"
                      checked={selectedUsers.includes(user.id)}
                      onChange={() => handleUserToggle(user.id)}
                      className="rounded border-gray-300 text-lblue focus:ring-lblue w-4 h-4 md:w-auto md:h-auto"
                    />
                    <div className="flex-1 min-w-0">
                      <div className="text-sm font-medium text-gray-900 truncate">
                        {user.name || 'Utilisateur'}
                      </div>
                      <div className="text-xs text-gray-500 truncate">{user.email}</div>
                    </div>
                  </label>
                ))}
              </div>
            )}
          </div>

          {/* Utilisateurs sélectionnés */}
          {selectedUsers.length > 0 && (
            <div>
              <div className="text-sm font-medium text-gray-700 mb-2">
                {selectedUsers.length} utilisateur{selectedUsers.length > 1 ? 's' : ''} sélectionné{selectedUsers.length > 1 ? 's' : ''}
              </div>
            </div>
          )}
        </div>

        <div className="p-4 md:p-6 border-t border-gray-200 flex flex-col-reverse md:flex-row justify-end gap-2 md:gap-3 flex-shrink-0">
          <button
            onClick={onClose}
            className="px-4 py-2 text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 transition-colors w-full md:w-auto"
          >
            Annuler
          </button>
          <button
            onClick={handleCreate}
            disabled={isCreating || selectedUsers.length === 0}
            className="px-4 py-2 bg-lblue text-white rounded-lg hover:bg-dblue transition-colors disabled:opacity-50 disabled:cursor-not-allowed w-full md:w-auto"
          >
            {isCreating ? 'Création...' : 'Créer'}
          </button>
        </div>
      </div>

      {/* Modal d'alerte */}
      {alertModal && (
        <AlertModal
          isOpen={alertModal.show}
          type={alertModal.type}
          title={alertModal.title}
          message={alertModal.message}
          onClose={() => setAlertModal(null)}
        />
      )}
    </div>
  );
}
