/**
 * Composant pour afficher la liste des collaborateurs d'une playlist
 * T0483: Create Playlist Share Modal Component
 */

// useState removed
import { Button } from '@/components/ui/button';
import { Select } from '@/components/ui/select';
import { Avatar } from '@/components/ui/avatar';
import {
  useRemoveCollaborator,
  useUpdateCollaboratorPermission,
} from '../hooks/usePlaylist';
import type { PlaylistCollaborator } from '../services/playlistService';
import { Trash2, Loader2 } from 'lucide-react';
import { useToast } from '@/hooks/useToast';
import { cn } from '@/lib/utils';

interface CollaboratorListProps {
  collaborators: PlaylistCollaborator[];
  playlistId: string;
  canManage?: boolean; // Si l'utilisateur peut gérer les collaborateurs (owner ou admin)
  className?: string;
}

export function CollaboratorList({
  collaborators,
  playlistId,
  canManage = false,
  className,
}: CollaboratorListProps) {
  const { success: showSuccess, error: showError } = useToast();
  const removeMutation = useRemoveCollaborator();
  const updatePermissionMutation = useUpdateCollaboratorPermission();

  const handleRemove = async (userId: string, username: string) => {
    if (
      !confirm(
        `Êtes-vous sûr de vouloir retirer ${username} de cette playlist ?`,
      )
    ) {
      return;
    }

    try {
      await removeMutation.mutateAsync({ playlistId, userId });
      showSuccess('Collaborateur retiré');
    } catch (error) {
      showError(
        error instanceof Error
          ? error.message
          : 'Impossible de retirer le collaborateur.',
      );
    }
  };

  const handlePermissionChange = async (
    userId: string,
    newPermission: 'read' | 'write' | 'admin',
    username: string,
  ) => {
    try {
      await updatePermissionMutation.mutateAsync({
        playlistId,
        userId,
        data: { permission: newPermission },
      });
      showSuccess(`Permission mise à jour pour ${username}`);
    } catch (error) {
      showError(
        error instanceof Error
          ? error.message
          : 'Impossible de mettre à jour la permission.',
      );
    }
  };

  if (collaborators.length === 0) {
    return (
      <div className={cn('text-center py-8 text-muted-foreground', className)}>
        <p>Aucun collaborateur pour le moment</p>
      </div>
    );
  }

  return (
    <div className={cn('space-y-2', className)}>
      {collaborators.map((collaborator) => {
        const isRemoving = removeMutation?.isPending || false;
        const isUpdating = updatePermissionMutation?.isPending || false;

        return (
          <div
            key={collaborator.id}
            className="flex items-center justify-between p-3 border rounded-lg hover:bg-accent/50 transition-colors"
          >
            <div className="flex items-center space-x-3 flex-1 min-w-0">
              <Avatar
                src={collaborator.user?.avatar_url}
                alt={collaborator.user?.username || 'User'}
                size="sm"
              />
              <div className="flex-1 min-w-0">
                <p className="font-medium truncate">
                  {collaborator.user?.username ||
                    `User #${collaborator.user_id}`}
                </p>
                {collaborator.user?.email && (
                  <p className="text-sm text-muted-foreground truncate">
                    {collaborator.user.email}
                  </p>
                )}
              </div>
            </div>

            <div className="flex items-center space-x-2">
              {canManage ? (
                <>
                  <Select
                    options={[
                      { value: 'read', label: 'Lecture' },
                      { value: 'write', label: 'Écriture' },
                      { value: 'admin', label: 'Admin' },
                    ]}
                    value={collaborator.permission}
                    onChange={(value) =>
                      handlePermissionChange(
                        collaborator.user_id,
                        value as 'read' | 'write' | 'admin',
                        collaborator.user?.username || 'User',
                      )
                    }
                    disabled={isUpdating}
                    className="w-32"
                  />
                  <Button
                    variant="ghost"
                    size="icon"
                    onClick={() =>
                      handleRemove(
                        collaborator.user_id,
                        collaborator.user?.username || 'User',
                      )
                    }
                    disabled={isRemoving}
                    className="text-destructive hover:text-destructive"
                  >
                    {isRemoving ? (
                      <Loader2 className="h-4 w-4 animate-spin" />
                    ) : (
                      <Trash2 className="h-4 w-4" />
                    )}
                  </Button>
                </>
              ) : (
                <span className="text-sm text-muted-foreground capitalize">
                  {collaborator.permission === 'read' && 'Lecture'}
                  {collaborator.permission === 'write' && 'Écriture'}
                  {collaborator.permission === 'admin' && 'Admin'}
                </span>
              )}
            </div>
          </div>
        );
      })}
    </div>
  );
}
