/**
 * Modal pour partager une playlist avec d'autres utilisateurs
 * T0483: Create Playlist Share Modal Component
 */

import { useState, useEffect, useCallback } from 'react';
import { Modal } from '@/components/ui/modal';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select } from '@/components/ui/select';
import { Avatar } from '@/components/ui/avatar';
import { useDebounce } from '@/hooks/useDebounce';
import { useToast } from '@/hooks/useToast';
import { useAddCollaborator, useCollaborators } from '../hooks/usePlaylist';
import { CollaboratorList } from './CollaboratorList';
import { apiClient } from '@/services/api/client';
import { Search, Loader2, UserPlus, X } from 'lucide-react';
import type { AxiosError } from 'axios';

interface User {
  id: number;
  username: string;
  email: string;
  avatar?: string;
}

interface SharePlaylistModalProps {
  open: boolean;
  onClose: () => void;
  playlistId: number;
  canManage?: boolean; // Si l'utilisateur peut gérer les collaborateurs
}

export function SharePlaylistModal({
  open,
  onClose,
  playlistId,
  canManage = true,
}: SharePlaylistModalProps) {
  const [searchQuery, setSearchQuery] = useState('');
  const [users, setUsers] = useState<User[]>([]);
  const [selectedUser, setSelectedUser] = useState<User | null>(null);
  const [selectedPermission, setSelectedPermission] = useState<'read' | 'write' | 'admin'>('read');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [addingCollaborator, setAddingCollaborator] = useState(false);

  const { toast } = useToast();
  const addCollaboratorMutation = useAddCollaborator();
  const { data: collaborators, isLoading: loadingCollaborators } = useCollaborators(playlistId);

  const debouncedQuery = useDebounce(searchQuery, 500);

  // Rechercher des utilisateurs
  const searchUsers = useCallback(async () => {
    if (!debouncedQuery.trim()) {
      setUsers([]);
      return;
    }

    setLoading(true);
    setError(null);

    try {
      const response = await apiClient.get<{ data: User[]; meta?: { total: number } }>(
        '/users/search',
        {
          params: {
            q: debouncedQuery.trim(),
            limit: 10,
          },
        }
      );
      setUsers(response.data.data || response.data);
    } catch (err) {
      const axiosError = err as AxiosError;
      const errorMessage =
        axiosError.response?.data?.error || 'Erreur lors de la recherche d\'utilisateurs';
      setError(errorMessage);
      setUsers([]);
    } finally {
      setLoading(false);
    }
  }, [debouncedQuery]);

  // Effectuer la recherche quand la query change
  useEffect(() => {
    if (open && debouncedQuery.trim()) {
      searchUsers();
    } else {
      setUsers([]);
    }
  }, [debouncedQuery, open, searchUsers]);

  // Réinitialiser quand le modal s'ouvre
  useEffect(() => {
    if (open) {
      setSearchQuery('');
      setSelectedUser(null);
      setSelectedPermission('read');
      setError(null);
      setUsers([]);
    }
  }, [open]);

  const handleAddCollaborator = async () => {
    if (!selectedUser) {
      toast({
        title: 'Erreur',
        description: 'Veuillez sélectionner un utilisateur.',
        variant: 'destructive',
      });
      return;
    }

    // Vérifier si l'utilisateur est déjà collaborateur
    if (collaborators?.some((c) => c.user_id === selectedUser.id)) {
      toast({
        title: 'Erreur',
        description: 'Cet utilisateur est déjà collaborateur de cette playlist.',
        variant: 'destructive',
      });
      return;
    }

    setAddingCollaborator(true);

    try {
      await addCollaboratorMutation.mutateAsync({
        playlistId,
        data: {
          user_id: selectedUser.id,
          permission: selectedPermission,
        },
      });

      toast({
        title: 'Collaborateur ajouté',
        description: `${selectedUser.username} a été ajouté à la playlist.`,
      });

      // Réinitialiser la sélection
      setSelectedUser(null);
      setSearchQuery('');
      setUsers([]);
    } catch (error) {
      toast({
        title: 'Erreur',
        description: error instanceof Error ? error.message : 'Impossible d\'ajouter le collaborateur.',
        variant: 'destructive',
      });
    } finally {
      setAddingCollaborator(false);
    }
  };

  const handleUserSelect = (user: User) => {
    setSelectedUser(user);
    setSearchQuery(user.username);
    setUsers([]);
  };

  return (
    <Modal open={open} onClose={onClose} title="Partager la playlist" size="lg">
      <div className="space-y-6">
        {/* Section: Ajouter un collaborateur */}
        {canManage && (
          <div className="space-y-4">
            <div>
              <Label htmlFor="user-search">Rechercher un utilisateur</Label>
              <div className="relative mt-2">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <Input
                  id="user-search"
                  type="text"
                  placeholder="Rechercher par nom d'utilisateur ou email..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-10"
                />
                {selectedUser && (
                  <Button
                    variant="ghost"
                    size="icon"
                    className="absolute right-2 top-1/2 transform -translate-y-1/2 h-6 w-6"
                    onClick={() => {
                      setSelectedUser(null);
                      setSearchQuery('');
                    }}
                  >
                    <X className="h-4 w-4" />
                  </Button>
                )}
              </div>

              {/* Résultats de recherche */}
              {searchQuery && !selectedUser && (
                <div className="mt-2 border rounded-lg max-h-[200px] overflow-y-auto">
                  {loading ? (
                    <div className="flex items-center justify-center p-4">
                      <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
                      <span className="ml-2 text-sm text-muted-foreground">Recherche...</span>
                    </div>
                  ) : error ? (
                    <div className="p-4 text-sm text-destructive">{error}</div>
                  ) : users.length === 0 ? (
                    <div className="p-4 text-sm text-muted-foreground text-center">
                      Aucun utilisateur trouvé
                    </div>
                  ) : (
                    <div className="divide-y">
                      {users.map((user) => (
                        <button
                          key={user.id}
                          type="button"
                          onClick={() => handleUserSelect(user)}
                          className="w-full flex items-center space-x-3 p-3 hover:bg-accent transition-colors text-left"
                        >
                          <Avatar src={user.avatar} alt={user.username} size="sm" />
                          <div className="flex-1 min-w-0">
                            <p className="font-medium truncate">{user.username}</p>
                            <p className="text-sm text-muted-foreground truncate">{user.email}</p>
                          </div>
                        </button>
                      ))}
                    </div>
                  )}
                </div>
              )}

              {/* Utilisateur sélectionné */}
              {selectedUser && (
                <div className="mt-2 p-3 border rounded-lg bg-accent/50">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-3">
                      <Avatar src={selectedUser.avatar} alt={selectedUser.username} size="sm" />
                      <div>
                        <p className="font-medium">{selectedUser.username}</p>
                        <p className="text-sm text-muted-foreground">{selectedUser.email}</p>
                      </div>
                    </div>
                  </div>
                </div>
              )}
            </div>

            {selectedUser && (
              <div className="space-y-2">
                <Label htmlFor="permission">Permission</Label>
                <Select
                  id="permission"
                  options={[
                    { value: 'read', label: 'Lecture - Peut voir la playlist' },
                    { value: 'write', label: 'Écriture - Peut modifier la playlist' },
                    { value: 'admin', label: 'Admin - Peut gérer les collaborateurs' },
                  ]}
                  value={selectedPermission}
                  onChange={(value) => setSelectedPermission(value as 'read' | 'write' | 'admin')}
                />
              </div>
            )}

            <Button
              onClick={handleAddCollaborator}
              disabled={!selectedUser || addingCollaborator}
              className="w-full"
            >
              {addingCollaborator ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Ajout en cours...
                </>
              ) : (
                <>
                  <UserPlus className="mr-2 h-4 w-4" />
                  Ajouter le collaborateur
                </>
              )}
            </Button>
          </div>
        )}

        {/* Section: Liste des collaborateurs */}
        <div className="space-y-2">
          <h3 className="font-semibold">Collaborateurs</h3>
          {loadingCollaborators ? (
            <div className="flex items-center justify-center p-8">
              <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
              <span className="ml-2 text-muted-foreground">Chargement...</span>
            </div>
          ) : (
            <CollaboratorList
              collaborators={collaborators || []}
              playlistId={playlistId}
              canManage={canManage}
            />
          )}
        </div>

        {/* Actions */}
        <div className="flex justify-end pt-4 border-t">
          <Button variant="outline" onClick={onClose}>
            Fermer
          </Button>
        </div>
      </div>
    </Modal>
  );
}

