import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { CollaboratorList } from './CollaboratorList';
import { AddCollaboratorModal } from './AddCollaboratorModal';
import { UserPlus, Users } from 'lucide-react';
import { useQuery } from '@tanstack/react-query';
import { playlistsApi, type PlaylistCollaborator } from '@/services/api/playlists';
import { LoadingSpinner } from '@/components/ui/loading-spinner';

/**
 * FE-COMP-011: Playlist collaborator management UI component
 * Combines add, remove, and update functionality in a unified interface
 */

export interface CollaboratorManagementProps {
  playlistId: string;
  canManage?: boolean;
  className?: string;
}

/**
 * Main component for managing playlist collaborators
 */
export function CollaboratorManagement({
  playlistId,
  canManage = false,
  className,
}: CollaboratorManagementProps) {
  const [isAddModalOpen, setIsAddModalOpen] = useState(false);

  // Fetch collaborators
  const {
    data: collaborators,
    isLoading,
    isError,
    error,
    refetch,
  } = useQuery<PlaylistCollaborator[]>({
    queryKey: ['playlist', playlistId, 'collaborators'],
    queryFn: () => playlistsApi.getCollaborators(playlistId),
    enabled: !!playlistId,
  });

  const handleCollaboratorAdded = () => {
    refetch();
  };

  if (isLoading) {
    return (
      <Card className={className}>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Users className="h-5 w-5" />
            Collaborateurs
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-center py-8">
            <LoadingSpinner />
          </div>
        </CardContent>
      </Card>
    );
  }

  if (isError) {
    return (
      <Card className={className}>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Users className="h-5 w-5" />
            Collaborateurs
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="text-center py-8 text-destructive">
            <p>Erreur lors du chargement des collaborateurs</p>
            {error instanceof Error && (
              <p className="text-sm mt-2">{error.message}</p>
            )}
            <Button
              variant="outline"
              size="sm"
              onClick={() => refetch()}
              className="mt-4"
            >
              Réessayer
            </Button>
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <>
      <Card className={className}>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle className="flex items-center gap-2">
              <Users className="h-5 w-5" />
              Collaborateurs
              {collaborators && collaborators.length > 0 && (
                <span className="text-sm font-normal text-muted-foreground">
                  ({collaborators.length})
                </span>
              )}
            </CardTitle>
            {canManage && (
              <Button
                variant="outline"
                size="sm"
                onClick={() => setIsAddModalOpen(true)}
              >
                <UserPlus className="h-4 w-4 mr-2" />
                Ajouter
              </Button>
            )}
          </div>
        </CardHeader>
        <CardContent>
          <CollaboratorList
            collaborators={collaborators || []}
            playlistId={playlistId}
            canManage={canManage}
          />
        </CardContent>
      </Card>

      {canManage && (
        <AddCollaboratorModal
          open={isAddModalOpen}
          onClose={() => setIsAddModalOpen(false)}
          playlistId={playlistId}
          onAdded={handleCollaboratorAdded}
        />
      )}
    </>
  );
}
