import React, { useState } from 'react';
import { Copy, Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useToast } from '@/hooks/useToast';
import { useNavigate } from 'react-router-dom';
import { apiClient } from '@/services/api/client';

interface DuplicatePlaylistButtonProps {
  playlistId: number;
  playlistTitle?: string;
  className?: string;
  variant?: 'default' | 'outline' | 'ghost' | 'link' | 'destructive' | 'secondary';
  size?: 'default' | 'sm' | 'lg' | 'icon';
}

/**
 * DuplicatePlaylistButton - Bouton pour dupliquer une playlist
 * T0495: Create Playlist Duplicate Feature
 */
export const DuplicatePlaylistButton: React.FC<DuplicatePlaylistButtonProps> = ({
  playlistId,
  playlistTitle = 'playlist',
  className,
  variant = 'outline',
  size = 'sm',
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const [isDuplicating, setIsDuplicating] = useState(false);
  const [newTitle, setNewTitle] = useState(`${playlistTitle} (Copy)`);
  const { toast } = useToast();
  const navigate = useNavigate();

  const handleDuplicate = async () => {
    if (!newTitle.trim()) {
      toast({
        title: 'Erreur',
        description: 'Le titre est requis',
        variant: 'destructive',
      });
      return;
    }

    setIsDuplicating(true);

    try {
      const response = await apiClient.post<{ message: string; playlist: any }>(
        `/playlists/${playlistId}/duplicate`,
        {
          new_title: newTitle,
        }
      );

      toast({
        title: 'Playlist dupliquée',
        description: 'La playlist a été dupliquée avec succès',
      });

      setIsOpen(false);
      setNewTitle(`${playlistTitle} (Copy)`);

      // Naviguer vers la nouvelle playlist
      if (response.data.playlist?.id) {
        navigate(`/playlists/${response.data.playlist.id}`);
      }
    } catch (error: any) {
      console.error('Duplicate error:', error);
      const errorMessage =
        error.response?.data?.error || error.message || 'Une erreur est survenue lors de la duplication';
      toast({
        title: 'Erreur de duplication',
        description: errorMessage,
        variant: 'destructive',
      });
    } finally {
      setIsDuplicating(false);
    }
  };

  const handleClose = () => {
    if (!isDuplicating) {
      setIsOpen(false);
      setNewTitle(`${playlistTitle} (Copy)`);
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={handleClose}>
      <DialogTrigger asChild>
        <Button variant={variant} size={size} className={className}>
          <Copy className="h-4 w-4 mr-2" />
          Dupliquer
        </Button>
      </DialogTrigger>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>Dupliquer la playlist</DialogTitle>
          <DialogDescription>
            Créez une copie de cette playlist avec tous ses tracks. Vous pouvez modifier le nom de la nouvelle playlist.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4 py-4">
          {/* Title */}
          <div className="space-y-2">
            <Label htmlFor="new_title">Nom de la nouvelle playlist *</Label>
            <Input
              id="new_title"
              value={newTitle}
              onChange={(e) => setNewTitle(e.target.value)}
              placeholder="Nom de la playlist"
              disabled={isDuplicating}
              required
            />
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={handleClose} disabled={isDuplicating}>
            Annuler
          </Button>
          <Button onClick={handleDuplicate} disabled={isDuplicating || !newTitle.trim()}>
            {isDuplicating ? (
              <>
                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                Duplication...
              </>
            ) : (
              <>
                <Copy className="h-4 w-4 mr-2" />
                Dupliquer
              </>
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

