import React, { useState, useRef } from 'react';
import { Upload, FileJson, FileSpreadsheet, Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Dialog } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useToast } from '@/hooks/useToast';
import { TokenStorage } from '@/services/tokenStorage';
import { logger } from '@/utils/logger';

import { useNavigate } from 'react-router-dom';

interface ImportPlaylistButtonProps {
  // FE-TYPE-001: IDs are strings (UUIDs), not numbers
  onImported?: (playlistId: string) => 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 { success: showSuccess, error: showError } = useToast();
  const navigate = useNavigate();

  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      const fileName = file.name.toLowerCase();
      if (!fileName.endsWith('.json') && !fileName.endsWith('.csv')) {
        showError('Le fichier doit être au format JSON ou CSV');
        return;
      }

      setSelectedFile(file);

      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
          }
        };
        reader.readAsText(file);
      }
    }
  };

  const handleImport = async () => {
    if (!selectedFile) {
      showError('Veuillez sélectionner un fichier');
      return;
    }

    if (!title.trim()) {
      showError('Le titre est requis');
      return;
    }

    setIsImporting(true);

    try {
      const token = TokenStorage.getAccessToken();
      if (!token) {
        showError('Vous devez être connecté pour importer une playlist');
        return;
      }

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

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

      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();

      showSuccess(
        `La playlist a été importée avec ${result.imported_tracks || 0} track(s)`,
      );

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

      if (result.playlist_id) {
        if (onImported) {
          onImported(result.playlist_id);
        } else {
          navigate(`/playlists/${result.playlist_id}`);
        }
      }
    } catch (error) {
      logger.error('Import error:', { error });
      showError(
        error instanceof Error
          ? error.message
          : "Une erreur est survenue lors de l'import",
      );
    } finally {
      setIsImporting(false);
    }
  };

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

  const footer = (
    <div className="flex justify-end gap-2">
      <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>
    </div>
  );

  return (
    <>
      <Button
        variant="outline"
        size="sm"
        className={className}
        onClick={() => setIsOpen(true)}
      >
        <Upload className="h-4 w-4 mr-2" />
        Importer
      </Button>

      <Dialog
        open={isOpen}
        onClose={handleClose}
        title="Importer une playlist"
        footer={footer}
      >
        <div className="space-y-4 py-4">
          <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>

          <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>

          <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>

          <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>
      </Dialog>
    </>
  );
};
