/**
 * Composant bouton pour supprimer un track d'une playlist
 * T0472: Create Remove Track from Playlist Component
 */

import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Dialog } from '@/components/ui/dialog';
import { useToast } from '@/hooks/useToast';
import { useRemoveTrackFromPlaylist } from '../hooks/usePlaylist';
import { Loader2, Trash2 } from 'lucide-react';
import { cn } from '@/lib/utils';

interface RemoveTrackButtonProps {
  playlistId: number;
  trackId: number;
  trackTitle?: string;
  onRemoved?: () => void;
  trigger?: React.ReactNode;
  variant?: 'default' | 'destructive' | 'outline' | 'ghost' | 'link';
  size?: 'default' | 'sm' | 'lg' | 'icon';
  className?: string;
}

export function RemoveTrackButton({
  playlistId,
  trackId,
  trackTitle,
  onRemoved,
  trigger,
  variant = 'ghost',
  size = 'default',
  className,
}: RemoveTrackButtonProps) {
  const [open, setOpen] = useState(false);
  const { toast } = useToast();
  const removeTrackMutation = useRemoveTrackFromPlaylist();

  const handleRemove = async () => {
    try {
      await removeTrackMutation.mutateAsync({
        playlistId,
        trackId,
      });
      toast({
        title: 'Track retiré',
        description: 'Le track a été retiré de la playlist avec succès.',
      });
      setOpen(false);
      onRemoved?.();
    } catch (error) {
      console.error('Failed to remove track from playlist:', error);
      let errorMessage = 'Impossible de retirer le track de la playlist';
      if (error instanceof Error) {
        errorMessage = error.message;
      }
      toast({
        title: 'Erreur',
        description: errorMessage,
        variant: 'destructive',
      });
      // Ne pas fermer le dialog en cas d'erreur pour permettre de réessayer
    }
  };

  const defaultTrigger = (
    <Button
      variant={variant}
      size={size}
      className={cn(className)}
      onClick={() => setOpen(true)}
    >
      <Trash2 className="h-4 w-4 mr-2" />
      Retirer
    </Button>
  );

  return (
    <>
      {trigger ? (
        <div onClick={() => setOpen(true)} className="cursor-pointer">
          {trigger}
        </div>
      ) : (
        defaultTrigger
      )}

      <Dialog
        open={open}
        onClose={() => {
          if (!removeTrackMutation.isPending) {
            setOpen(false);
          }
        }}
        title="Retirer le track de la playlist ?"
        variant="alert"
        onConfirm={handleRemove}
        onCancel={() => setOpen(false)}
        confirmLabel={removeTrackMutation.isPending ? 'Retrait...' : 'Retirer'}
        cancelLabel="Annuler"
        showCancel={true}
        size="md"
      >
        <div className="space-y-4">
          <p className="text-sm text-muted-foreground">
            Le track sera retiré de la playlist. Cette action peut être annulée en ajoutant à nouveau le track.
          </p>
          {trackTitle && (
            <div className="p-3 bg-muted rounded-md">
              <p className="text-sm font-medium">Track à retirer :</p>
              <p className="text-sm text-muted-foreground mt-1">{trackTitle}</p>
            </div>
          )}
          {removeTrackMutation.isPending && (
            <div className="flex items-center gap-2 text-sm text-muted-foreground">
              <Loader2 className="h-4 w-4 animate-spin" />
              <span>Retrait en cours...</span>
            </div>
          )}
        </div>
      </Dialog>
    </>
  );
}

