import { useState } from 'react';
import { deleteTrack, TrackUploadError } from '../services/trackService';
import { Button } from '@/components/ui/button';
import { Dialog } from '@/components/ui/dialog';
import { useToast } from '@/hooks/useToast';
import { Trash2, Loader2 } from 'lucide-react';

/**
 * TrackDelete Component
 * T0279: Composant pour supprimer un track avec confirmation
 */

interface TrackDeleteProps {
  trackId: number;
  trackTitle?: string;
  onDelete?: () => void;
  trigger?: React.ReactNode;
  className?: string;
}

export function TrackDelete({ 
  trackId, 
  trackTitle, 
  onDelete, 
  trigger,
  className 
}: TrackDeleteProps) {
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const { toast } = useToast();

  const handleDelete = async () => {
    setLoading(true);
    try {
      await deleteTrack(trackId);
      toast.success('Track supprimé avec succès');
      // Close dialog only on success
      setOpen(false);
      onDelete?.();
    } catch (error) {
      console.error('Failed to delete track:', error);
      let errorMessage = 'Impossible de supprimer le track';
      if (error instanceof TrackUploadError) {
        errorMessage = error.message;
      }
      toast.error(errorMessage);
      // Keep dialog open on error so user can retry or cancel
      // The Dialog will close automatically on success, but we prevent it on error
      // by not closing setOpen(false) here
      throw error; // Re-throw to prevent Dialog from closing automatically
    } finally {
      setLoading(false);
    }
  };

  const defaultTrigger = (
    <Button variant="destructive" size="sm" className={className}>
      <Trash2 className="h-4 w-4 mr-2" />
      Supprimer
    </Button>
  );

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

      <Dialog
        open={open}
        onClose={() => {
          if (!loading) {
            setOpen(false);
          }
        }}
        title="Supprimer le track ?"
        variant="alert"
        onConfirm={handleDelete}
        onCancel={() => setOpen(false)}
        confirmLabel={loading ? 'Suppression...' : 'Supprimer'}
        cancelLabel="Annuler"
        showCancel={true}
        size="md"
      >
        <div className="space-y-4">
          <p className="text-sm text-muted-foreground">
            Cette action est irréversible. Le track et tous ses fichiers seront supprimés définitivement.
          </p>
          {trackTitle && (
            <div className="p-3 bg-muted rounded-md">
              <p className="text-sm font-medium">Track à supprimer :</p>
              <p className="text-sm text-muted-foreground mt-1">{trackTitle}</p>
            </div>
          )}
          {loading && (
            <div className="flex items-center gap-2 text-sm text-muted-foreground">
              <Loader2 className="h-4 w-4 animate-spin" />
              <span>Suppression en cours...</span>
            </div>
          )}
        </div>
      </Dialog>
    </>
  );
}

