import { useState, useRef } from 'react';
import { X, Upload, FileJson, AlertCircle, CheckCircle } from 'lucide-react';
import { Button, Spinner } from '@/shared/components/ui';
import { api } from '@/shared/lib/api';

interface ImportCharacterModalProps {
  campaignId: string;
  onClose: () => void;
  onImported: () => void;
}

interface PathbuilderJson {
  success: boolean;
  build: {
    name: string;
    class: string;
    level: number;
    ancestry: string;
    heritage: string;
    background: string;
  };
}

export function ImportCharacterModal({ campaignId, onClose, onImported }: ImportCharacterModalProps) {
  const [jsonText, setJsonText] = useState('');
  const [parsedData, setParsedData] = useState<PathbuilderJson | null>(null);
  const [error, setError] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [importSuccess, setImportSuccess] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const validateAndParseJson = (text: string) => {
    try {
      const data = JSON.parse(text);

      // Validate Pathbuilder structure
      if (!data.build) {
        throw new Error('Kein "build" Objekt gefunden. Ist das eine Pathbuilder Export-Datei?');
      }

      if (!data.build.name || !data.build.class || !data.build.level) {
        throw new Error('Fehlende Pflichtfelder (name, class, level)');
      }

      setParsedData(data);
      setError('');
      return data;
    } catch (err) {
      if (err instanceof SyntaxError) {
        setError('Ungültiges JSON Format');
      } else if (err instanceof Error) {
        setError(err.message);
      }
      setParsedData(null);
      return null;
    }
  };

  const handleTextChange = (text: string) => {
    setJsonText(text);
    if (text.trim()) {
      validateAndParseJson(text);
    } else {
      setParsedData(null);
      setError('');
    }
  };

  const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    if (file.size > 1024 * 1024) {
      setError('Datei ist zu groß (max. 1MB)');
      return;
    }

    const reader = new FileReader();
    reader.onload = (event) => {
      const text = event.target?.result as string;
      setJsonText(text);
      validateAndParseJson(text);
    };
    reader.onerror = () => {
      setError('Fehler beim Lesen der Datei');
    };
    reader.readAsText(file);
  };

  const handleImport = async () => {
    if (!parsedData) return;

    setIsSubmitting(true);
    setError('');

    try {
      await api.importCharacterFromPathbuilder(campaignId, parsedData);
      setImportSuccess(true);
      setTimeout(() => {
        onImported();
        onClose();
      }, 1500);
    } catch (err) {
      console.error('Import failed:', err);
      setError('Import fehlgeschlagen. Bitte versuche es erneut.');
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      <div className="absolute inset-0 bg-black/50" onClick={onClose} />
      <div className="relative bg-bg-primary border border-border rounded-xl p-6 w-full max-w-2xl mx-4 shadow-xl max-h-[90vh] overflow-y-auto">
        <div className="flex items-center justify-between mb-6">
          <h2 className="text-lg font-semibold text-text-primary flex items-center gap-2">
            <FileJson className="h-5 w-5 text-primary-500" />
            Pathbuilder Import
          </h2>
          <Button variant="ghost" size="icon" onClick={onClose}>
            <X className="h-5 w-5" />
          </Button>
        </div>

        {importSuccess ? (
          <div className="flex flex-col items-center justify-center py-12 text-center">
            <CheckCircle className="h-16 w-16 text-green-500 mb-4" />
            <h3 className="text-xl font-semibold text-text-primary mb-2">
              Import erfolgreich!
            </h3>
            <p className="text-text-secondary">
              {parsedData?.build.name} wurde importiert.
            </p>
          </div>
        ) : (
          <>
            {/* File Upload */}
            <div className="mb-4">
              <input
                ref={fileInputRef}
                type="file"
                accept=".json"
                onChange={handleFileUpload}
                className="hidden"
              />
              <Button
                type="button"
                variant="outline"
                className="w-full"
                onClick={() => fileInputRef.current?.click()}
              >
                <Upload className="h-4 w-4 mr-2" />
                JSON-Datei hochladen
              </Button>
            </div>

            <div className="relative mb-4">
              <div className="absolute inset-0 flex items-center">
                <div className="w-full border-t border-border" />
              </div>
              <div className="relative flex justify-center text-sm">
                <span className="px-2 bg-bg-primary text-text-secondary">oder</span>
              </div>
            </div>

            {/* JSON Text Area */}
            <div className="mb-4">
              <label className="block text-sm font-medium text-text-primary mb-1.5">
                JSON einfügen
              </label>
              <textarea
                value={jsonText}
                onChange={(e) => handleTextChange(e.target.value)}
                placeholder='{"success": true, "build": {...}}'
                rows={8}
                className="w-full px-3 py-2 bg-bg-secondary border border-border rounded-lg text-text-primary placeholder:text-text-muted focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent font-mono text-sm"
              />
            </div>

            {/* Error Message */}
            {error && (
              <div className="mb-4 p-3 rounded-lg bg-red-500/10 border border-red-500/20 text-red-500 text-sm flex items-start gap-2">
                <AlertCircle className="h-5 w-5 flex-shrink-0 mt-0.5" />
                <span>{error}</span>
              </div>
            )}

            {/* Preview */}
            {parsedData && (
              <div className="mb-6 p-4 rounded-lg bg-bg-secondary border border-border">
                <h3 className="text-sm font-medium text-text-primary mb-3">Vorschau</h3>
                <div className="grid grid-cols-2 gap-2 text-sm">
                  <div>
                    <span className="text-text-secondary">Name:</span>{' '}
                    <span className="text-text-primary font-medium">{parsedData.build.name}</span>
                  </div>
                  <div>
                    <span className="text-text-secondary">Level:</span>{' '}
                    <span className="text-text-primary font-medium">{parsedData.build.level}</span>
                  </div>
                  <div>
                    <span className="text-text-secondary">Klasse:</span>{' '}
                    <span className="text-text-primary font-medium">{parsedData.build.class}</span>
                  </div>
                  <div>
                    <span className="text-text-secondary">Abstammung:</span>{' '}
                    <span className="text-text-primary font-medium">{parsedData.build.ancestry}</span>
                  </div>
                  <div>
                    <span className="text-text-secondary">Erbe:</span>{' '}
                    <span className="text-text-primary font-medium">{parsedData.build.heritage}</span>
                  </div>
                  <div>
                    <span className="text-text-secondary">Hintergrund:</span>{' '}
                    <span className="text-text-primary font-medium">{parsedData.build.background}</span>
                  </div>
                </div>
              </div>
            )}

            {/* Actions */}
            <div className="flex justify-end gap-3">
              <Button type="button" variant="outline" onClick={onClose}>
                Abbrechen
              </Button>
              <Button
                onClick={handleImport}
                disabled={!parsedData || isSubmitting}
              >
                {isSubmitting ? (
                  <>
                    <Spinner size="sm" />
                    <span className="ml-2">Importiere...</span>
                  </>
                ) : (
                  'Importieren'
                )}
              </Button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}
