'use client';

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

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

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

interface Conversation {
  id: string;
  name: string | null;
  type: string;
  displayName: string;
  participants: Participant[];
}

interface GroupSettingsModalProps {
  conversation: Conversation;
  onClose: () => void;
  onUpdate: () => void;
}

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

export default function GroupSettingsModal({
  conversation,
  onClose,
  onUpdate,
}: GroupSettingsModalProps) {
  const [groupName, setGroupName] = useState(conversation.name || '');
  const [search, setSearch] = useState('');
  const [selectedUsers, setSelectedUsers] = useState<string[]>([]);
  const [isUpdating, setIsUpdating] = useState(false);
  const [isAdding, setIsAdding] = useState(false);
  const [alertModal, setAlertModal] = useState<{
    show: boolean;
    type: 'success' | 'error' | 'info' | 'warning';
    title: string;
    message: string;
  } | null>(null);
  const [confirmModal, setConfirmModal] = useState<{
    show: boolean;
    userId: string | null;
  } | null>(null);

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

  const existingParticipantIds = conversation.participants.map((p) => p.id);

  const handleUpdateName = async () => {
    if (!groupName.trim()) {
      setAlertModal({
        show: true,
        type: 'warning',
        title: 'Nom requis',
        message: 'Le nom du groupe ne peut pas être vide',
      });
      return;
    }

    setIsUpdating(true);
    try {
      const response = await fetch(`/api/conversations/${conversation.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ name: groupName }),
      });

      if (response.ok) {
        onUpdate();
        onClose();
      } else {
        const error = await response.json();
        setAlertModal({
          show: true,
          type: 'error',
          title: 'Erreur',
          message: error.error || 'Erreur lors de la mise à jour',
        });
      }
    } catch (error) {
      console.error('Erreur:', error);
      setAlertModal({
        show: true,
        type: 'error',
        title: 'Erreur',
        message: 'Erreur lors de la mise à jour',
      });
    } finally {
      setIsUpdating(false);
    }
  };

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

    setIsAdding(true);
    try {
      const response = await fetch(`/api/conversations/${conversation.id}/participants`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ userIds: selectedUsers }),
      });

      if (response.ok) {
        setSelectedUsers([]);
        setSearch('');
        onUpdate();
      } else {
        const error = await response.json();
        setAlertModal({
          show: true,
          type: 'error',
          title: 'Erreur',
          message: error.error || 'Erreur lors de l\'ajout des participants',
        });
      }
    } catch (error) {
      console.error('Erreur:', error);
      setAlertModal({
        show: true,
        type: 'error',
        title: 'Erreur',
        message: 'Erreur lors de l\'ajout des participants',
      });
    } finally {
      setIsAdding(false);
    }
  };

  const handleRemoveParticipant = async (userId: string) => {
    setConfirmModal({
      show: true,
      userId,
    });
  };

  const confirmRemoveParticipant = async () => {
    if (!confirmModal?.userId) return;

    try {
      const response = await fetch(
        `/api/conversations/${conversation.id}/participants?userId=${confirmModal.userId}`,
        {
          method: 'DELETE',
        }
      );

      if (response.ok) {
        onUpdate();
        setConfirmModal(null);
      } else {
        const error = await response.json();
        setAlertModal({
          show: true,
          type: 'error',
          title: 'Erreur',
          message: error.error || 'Erreur lors du retrait du participant',
        });
        setConfirmModal(null);
      }
    } catch (error) {
      console.error('Erreur:', error);
      setAlertModal({
        show: true,
        type: 'error',
        title: 'Erreur',
        message: 'Erreur lors du retrait du participant',
      });
      setConfirmModal(null);
    }
  };

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

  const availableUsers = users?.filter((u) => !existingParticipantIds.includes(u.id)) || [];

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
      <div className="bg-white rounded-lg shadow-xl w-full max-w-2xl mx-4 max-h-[90vh] flex flex-col">
        <div className="p-6 border-b border-gray-200">
          <div className="flex items-center justify-between">
            <h2 className="text-xl font-semibold text-gray-900">Paramètres du groupe</h2>
            <button
              onClick={onClose}
              className="text-gray-400 hover:text-gray-600 transition-colors"
            >
              <svg className="w-6 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-6 space-y-6">
          {/* Nom du groupe */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Nom du groupe
            </label>
            <div className="flex gap-2">
              <input
                type="text"
                value={groupName}
                onChange={(e) => setGroupName(e.target.value)}
                className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-lblue focus:border-transparent"
              />
              <button
                onClick={handleUpdateName}
                disabled={isUpdating || groupName.trim() === conversation.name}
                className="px-4 py-2 bg-lblue text-white rounded-lg hover:bg-dblue transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {isUpdating ? 'Mise à jour...' : 'Mettre à jour'}
              </button>
            </div>
          </div>

          {/* Participants existants */}
          <div>
            <h3 className="text-sm font-medium text-gray-700 mb-3">
              Participants ({conversation.participants.length})
            </h3>
            <div className="space-y-2">
              {conversation.participants.map((participant) => (
                <div
                  key={participant.id}
                  className="flex items-center justify-between p-3 bg-gray-50 rounded-lg"
                >
                  <div>
                    <div className="text-sm font-medium text-gray-900">
                      {participant.name || 'Utilisateur'}
                    </div>
                    <div className="text-xs text-gray-500">{participant.email}</div>
                  </div>
                  <button
                    onClick={() => handleRemoveParticipant(participant.id)}
                    className="text-red-600 hover:text-red-700 text-sm"
                  >
                    Retirer
                  </button>
                </div>
              ))}
            </div>
          </div>

          {/* Ajouter des participants */}
          <div>
            <h3 className="text-sm font-medium text-gray-700 mb-3">Ajouter des participants</h3>
            <div className="space-y-3">
              <input
                type="text"
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                placeholder="Rechercher des utilisateurs..."
                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"
              />
              {search && (
                <>
                  {error && (
                    <div className="text-sm text-red-600">Erreur lors de la recherche</div>
                  )}
                  {!users && !error && (
                    <div className="text-sm text-gray-500">Recherche...</div>
                  )}
                  {availableUsers.length === 0 && users && (
                    <div className="text-sm text-gray-500">
                      Aucun utilisateur disponible ou déjà dans le groupe
                    </div>
                  )}
                  {availableUsers.length > 0 && (
                    <>
                      <div className="max-h-48 overflow-y-auto border border-gray-200 rounded-lg divide-y divide-gray-100">
                        {availableUsers.map((user) => (
                          <label
                            key={user.id}
                            className="flex items-center gap-3 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"
                            />
                            <div className="flex-1">
                              <div className="text-sm font-medium text-gray-900">
                                {user.name || 'Utilisateur'}
                              </div>
                              <div className="text-xs text-gray-500">{user.email}</div>
                            </div>
                          </label>
                        ))}
                      </div>
                      {selectedUsers.length > 0 && (
                        <button
                          onClick={handleAddParticipants}
                          disabled={isAdding}
                          className="w-full px-4 py-2 bg-lblue text-white rounded-lg hover:bg-dblue transition-colors disabled:opacity-50"
                        >
                          {isAdding
                            ? 'Ajout...'
                            : `Ajouter ${selectedUsers.length} participant${selectedUsers.length > 1 ? 's' : ''}`}
                        </button>
                      )}
                    </>
                  )}
                </>
              )}
            </div>
          </div>
        </div>

        <div className="p-6 border-t border-gray-200">
          <button
            onClick={onClose}
            className="w-full px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors"
          >
            Fermer
          </button>
        </div>
      </div>

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

      {/* Modal de confirmation */}
      {confirmModal && (
        <ConfirmModal
          isOpen={confirmModal.show}
          title="Retirer un participant"
          message="Êtes-vous sûr de vouloir retirer cet utilisateur du groupe ?"
          confirmText="Retirer"
          cancelText="Annuler"
          confirmColor="danger"
          onConfirm={confirmRemoveParticipant}
          onCancel={() => setConfirmModal(null)}
        />
      )}
    </div>
  );
}
