'use client';

import { useState, useEffect } from 'react';
import { Modal, ModalFooter } from '@/components/ui';
import { Button } from '@/components/ui';
import { Input } from '@/components/ui';
import { Select } from '@/components/ui';
import type { TeamRole } from '@/lib/types';
import { TEAM_ROLE_LABELS } from '@/lib/types';

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

interface AddMemberModalProps {
  teamId: string;
  existingMemberIds: string[];
  onClose: () => void;
  onSuccess: () => void;
}

export function AddMemberModal({ teamId, existingMemberIds, onClose, onSuccess }: AddMemberModalProps) {
  const [users, setUsers] = useState<User[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedUserId, setSelectedUserId] = useState<string | null>(null);
  const [role, setRole] = useState<TeamRole>('MEMBER');
  const [loading, setLoading] = useState(false);
  const [fetchingUsers, setFetchingUsers] = useState(false);

  useEffect(() => {
    // Fetch all users
    setFetchingUsers(true);
    fetch('/api/users')
      .then((res) => res.json())
      .then((data) => {
        // Filter out existing members
        const availableUsers = data.filter((user: User) => !existingMemberIds.includes(user.id));
        setUsers(availableUsers);
      })
      .catch((error) => {
        console.error('Error fetching users:', error);
      })
      .finally(() => {
        setFetchingUsers(false);
      });
  }, [existingMemberIds]);

  const filteredUsers = users.filter(
    (user) =>
      user.email.toLowerCase().includes(searchTerm.toLowerCase()) ||
      user.name?.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!selectedUserId) {
      alert('Veuillez sélectionner un utilisateur');
      return;
    }

    setLoading(true);
    try {
      const response = await fetch(`/api/teams/${teamId}/members`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ userId: selectedUserId, role }),
      });

      if (!response.ok) {
        const error = await response.json();
        alert(error.error || 'Erreur lors de l\'ajout du membre');
        return;
      }

      onSuccess();
      onClose();
    } catch (error) {
      console.error('Error adding member:', error);
      alert('Erreur lors de l\'ajout du membre');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal isOpen={true} onClose={onClose} title="Ajouter un membre" size="md">
      <form onSubmit={handleSubmit}>
        <div className="space-y-4">
          {/* User Search */}
          <div>
            <label className="block text-sm font-medium text-foreground mb-2">
              Rechercher un utilisateur
            </label>
            <Input
              type="text"
              placeholder="Email ou nom..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              disabled={fetchingUsers}
            />
          </div>

          {/* User List */}
          {fetchingUsers ? (
            <div className="text-center py-4 text-muted">Chargement...</div>
          ) : filteredUsers.length === 0 ? (
            <div className="text-center py-4 text-muted">
              {searchTerm ? 'Aucun utilisateur trouvé' : 'Aucun utilisateur disponible'}
            </div>
          ) : (
            <div className="max-h-60 overflow-y-auto border border-border rounded-lg">
              {filteredUsers.map((user) => (
                <button
                  key={user.id}
                  type="button"
                  onClick={() => setSelectedUserId(user.id)}
                  className={`
                    w-full text-left px-4 py-3 hover:bg-card-hover transition-colors
                    ${selectedUserId === user.id ? 'bg-primary/10 border-l-2 border-primary' : ''}
                  `}
                >
                  <div className="font-medium text-foreground">{user.name || 'Sans nom'}</div>
                  <div className="text-sm text-muted">{user.email}</div>
                </button>
              ))}
            </div>
          )}

          {/* Role Selection */}
          <Select
            label="Rôle"
            value={role}
            onChange={(e) => setRole(e.target.value as TeamRole)}
            options={[
              { value: 'MEMBER', label: TEAM_ROLE_LABELS.MEMBER },
              { value: 'ADMIN', label: TEAM_ROLE_LABELS.ADMIN },
            ]}
          />
        </div>

        <ModalFooter>
          <Button type="button" variant="outline" onClick={onClose}>
            Annuler
          </Button>
          <Button
            type="submit"
            disabled={!selectedUserId || loading}
            className="bg-[var(--purple)] text-white hover:opacity-90 border-transparent"
          >
            {loading ? 'Ajout...' : 'Ajouter'}
          </Button>
        </ModalFooter>
      </form>
    </Modal>
  );
}

