import React, { useState, useRef } from 'react';
import { Upload, FileJson, FileSpreadsheet, 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 { Textarea } from '@/components/ui/textarea';
import { Switch } from '@/components/ui/switch';
import { useToast } from '@/hooks/useToast';
import { useCreatePlaylist } from '../hooks/usePlaylist';
import { useNavigate } from 'react-router-dom';

interface ImportPlaylistButtonProps {
  onImported?: (playlistId: number) => void;
  className?: string;
}

/**
 * ImportPlaylistButton - Bouton pour importer une playlist depuis un fichier JSON ou CSV
 * T0494: Create Playlist Import Feature
 */
export const ImportPlaylistButton: React.FC<ImportPlaylistButtonProps> = ({
  onImported,
  className,
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const [isImporting, setIsImporting] = useState(false);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [isPublic, setIsPublic] = useState(true);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const { toast } = useToast();
  const navigate = useNavigate();

  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      // Vérifier l'extension
      const fileName = file.name.toLowerCase();
      if (!fileName.endsWith('.json') && !fileName.endsWith('.csv')) {
        toast({
          title: 'Erreur',
          description: 'Le fichier doit être au format JSON ou CSV',
          variant: 'destructive',
        });
        return;
      }

      setSelectedFile(file);

      // Si c'est un JSON, essayer d'extraire le titre
      if (fileName.endsWith('.json')) {
        const reader = new FileReader();
        reader.onload = (e) => {
          try {
            const content = e.target?.result as string;
            const data = JSON.parse(content);
            if (data.playlist?.title && !title) {
              setTitle(data.playlist.title);
            }
            if (data.playlist?.description && !description) {
              setDescription(data.playlist.description);
            }
            if (data.playlist?.is_public !== undefined) {
              setIsPublic(data.playlist.is_public);
            }
          } catch (error) {
            // Ignorer les erreurs de parsing, l'utilisateur pourra entrer le titre manuellement
          }
        };
        reader.readAsText(file);
      }
    }
  };

  const handleImport = async () => {
    if (!selectedFile) {
      toast({
        title: 'Erreur',
        description: 'Veuillez sélectionner un fichier',
        variant: 'destructive',
      });
      return;
    }

    if (!title.trim()) {
      toast({
        title: 'Erreur',
        description: 'Le titre est requis',
        variant: 'destructive',
      });
      return;
    }

    setIsImporting(true);

    try {
      const token = localStorage.getItem('token');
      if (!token) {
        toast({
          title: 'Erreur',
          description: 'Vous devez être connecté pour importer une playlist',
          variant: 'destructive',
        });
        return;
      }

      // Déterminer le format
      const fileName = selectedFile.name.toLowerCase();
      const format = fileName.endsWith('.json') ? 'json' : 'csv';
      const url = `/api/v1/playlists/import/${format}`;

      // Créer le FormData
      const formData = new FormData();
      formData.append('file', selectedFile);
      formData.append('title', title);
      if (description) {
        formData.append('description', description);
      }
      formData.append('is_public', isPublic.toString());

      // Faire la requête
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
        },
        body: formData,
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.error || 'Erreur lors de l\'import');
      }

      const result = await response.json();

      toast({
        title: 'Import réussi',
        description: `La playlist a été importée avec ${result.imported_tracks || 0} track(s)`,
      });

      // Réinitialiser le formulaire
      setSelectedFile(null);
      setTitle('');
      setDescription('');
      setIsPublic(true);
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
      setIsOpen(false);

      // Appeler le callback ou naviguer
      if (result.playlist_id) {
        if (onImported) {
          onImported(result.playlist_id);
        } else {
          navigate(`/playlists/${result.playlist_id}`);
        }
      }
    } catch (error) {
      console.error('Import error:', error);
      toast({
        title: 'Erreur d\'import',
        description: error instanceof Error ? error.message : 'Une erreur est survenue lors de l\'import',
        variant: 'destructive',
      });
    } finally {
      setIsImporting(false);
    }
  };

  const handleClose = () => {
    if (!isImporting) {
      setIsOpen(false);
      setSelectedFile(null);
      setTitle('');
      setDescription('');
      setIsPublic(true);
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={handleClose}>
      <DialogTrigger asChild>
        <Button variant="outline" size="sm" className={className}>
          <Upload className="h-4 w-4 mr-2" />
          Importer
        </Button>
      </DialogTrigger>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>Importer une playlist</DialogTitle>
          <DialogDescription>
            Importez une playlist depuis un fichier JSON ou CSV exporté précédemment.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4 py-4">
          {/* File Selection */}
          <div className="space-y-2">
            <Label htmlFor="file">Fichier (JSON ou CSV)</Label>
            <div className="flex items-center gap-2">
              <Input
                id="file"
                type="file"
                accept=".json,.csv"
                onChange={handleFileSelect}
                ref={fileInputRef}
                disabled={isImporting}
                className="flex-1"
              />
              {selectedFile && (
                <div className="flex items-center gap-1 text-sm text-muted-foreground">
                  {selectedFile.name.toLowerCase().endsWith('.json') ? (
                    <FileJson className="h-4 w-4" />
                  ) : (
                    <FileSpreadsheet className="h-4 w-4" />
                  )}
                  <span className="max-w-[150px] truncate">{selectedFile.name}</span>
                </div>
              )}
            </div>
          </div>

          {/* Title */}
          <div className="space-y-2">
            <Label htmlFor="title">Titre *</Label>
            <Input
              id="title"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              placeholder="Nom de la playlist"
              disabled={isImporting}
              required
            />
          </div>

          {/* Description */}
          <div className="space-y-2">
            <Label htmlFor="description">Description</Label>
            <textarea
              id="description"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="Description de la playlist (optionnel)"
              disabled={isImporting}
              rows={3}
              className="flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
            />
          </div>

          {/* Is Public */}
          <div className="flex items-center justify-between">
            <Label htmlFor="is_public">Playlist publique</Label>
            <input
              type="checkbox"
              id="is_public"
              checked={isPublic}
              onChange={(e) => setIsPublic(e.target.checked)}
              disabled={isImporting}
              className="h-4 w-4 rounded border-gray-300 text-primary focus:ring-2 focus:ring-primary"
            />
          </div>
        </div>

        <DialogFooter>
          <Button
            variant="outline"
            onClick={handleClose}
            disabled={isImporting}
          >
            Annuler
          </Button>
          <Button
            onClick={handleImport}
            disabled={isImporting || !selectedFile || !title.trim()}
          >
            {isImporting ? (
              <>
                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                Import...
              </>
            ) : (
              <>
                <Upload className="h-4 w-4 mr-2" />
                Importer
              </>
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

