import { useRef } from 'react';
import type { CharacterData } from '../../../../types/CharacterJson.ts';

interface ImportButtonProps {
  onFileLoad: (data: CharacterData) => void;
}

export default function ImportButton({ onFileLoad }: ImportButtonProps) {
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    
    if (!file) return;
    
    // Check if the file is a JSON file
    if (file.type !== 'application/json') {
      alert('Please select a JSON file');
      return;
    }
    
    try {
      // Read the file content
      const fileContent = await file.text();
      
      // Parse and validate the JSON
      const parsedData = JSON.parse(fileContent) as CharacterData;
      
      // Call the callback to update the parent component's state
      onFileLoad(parsedData);
    } catch (error) {
      alert('Invalid JSON file. Please select a valid JSON file.');
      console.error('Error processing file:', error);
    }
    
    // Reset the input
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  return (
    <div className="relative">
      <input
        ref={fileInputRef}
        type="file"
        accept=".json"
        onChange={handleFileChange}
        className="hidden"
        id="character-import"
      />
      <label
        htmlFor="character-import"
        className="cursor-pointer bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg transition-colors duration-200"
      >
        Charakter laden
      </label>
    </div>
  );
}
