/**
 * ConfigImporter - Import optimization configs into canvas
 *
 * Supports:
 * - File upload (optimization_config.json)
 * - Paste JSON directly
 * - Load from study directory
 */

import { useState, useRef } from 'react';
import { useCanvasStore, OptimizationConfig } from '../../../hooks/useCanvasStore';

interface ConfigImporterProps {
  isOpen: boolean;
  onClose: () => void;
  onImport: (source: string) => void;
}

export function ConfigImporter({ isOpen, onClose, onImport }: ConfigImporterProps) {
  const [tab, setTab] = useState<'file' | 'paste' | 'study'>('file');
  const [jsonText, setJsonText] = useState('');
  const [studyPath, setStudyPath] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const { loadFromConfig } = useCanvasStore();

  if (!isOpen) return null;

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

    setError(null);
    setIsLoading(true);

    try {
      const text = await file.text();
      const config = JSON.parse(text) as OptimizationConfig;
      validateConfig(config);
      loadFromConfig(config);
      onImport(`File: ${file.name}`);
      handleClose();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Invalid JSON file');
    } finally {
      setIsLoading(false);
    }
  };

  const handlePasteImport = () => {
    setError(null);

    try {
      const config = JSON.parse(jsonText) as OptimizationConfig;
      validateConfig(config);
      loadFromConfig(config);
      onImport('Pasted JSON');
      handleClose();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Invalid JSON');
    }
  };

  const handleStudyLoad = async () => {
    setError(null);
    setIsLoading(true);

    try {
      // Call backend API to load study config
      const response = await fetch(`/api/studies/${encodeURIComponent(studyPath)}/config`);

      if (!response.ok) {
        throw new Error(`Study not found: ${studyPath}`);
      }

      const config = await response.json() as OptimizationConfig;
      validateConfig(config);
      loadFromConfig(config);
      onImport(`Study: ${studyPath}`);
      handleClose();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load study');
    } finally {
      setIsLoading(false);
    }
  };

  const validateConfig = (config: OptimizationConfig) => {
    if (!config) {
      throw new Error('Empty configuration');
    }

    // Must have at least one design variable or objective
    const hasDesignVars = config.design_variables && config.design_variables.length > 0;
    const hasObjectives = config.objectives && config.objectives.length > 0;

    if (!hasDesignVars && !hasObjectives) {
      throw new Error('Configuration must have design variables or objectives');
    }
  };

  const handleClose = () => {
    setJsonText('');
    setStudyPath('');
    setError(null);
    setTab('file');
    onClose();
  };

  return (
    <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 backdrop-blur-sm">
      <div className="bg-dark-850 rounded-xl shadow-2xl w-full max-w-lg border border-dark-700">
        {/* Header */}
        <div className="px-6 py-4 border-b border-dark-700 flex justify-between items-center">
          <h2 className="text-xl font-semibold text-white">Import Configuration</h2>
          <button
            onClick={handleClose}
            className="text-dark-400 hover:text-white text-xl transition-colors"
          >
            &times;
          </button>
        </div>

        {/* Tabs */}
        <div className="flex border-b border-dark-700">
          {[
            { id: 'file', label: 'Upload File' },
            { id: 'paste', label: 'Paste JSON' },
            { id: 'study', label: 'Load Study' },
          ].map((t) => (
            <button
              key={t.id}
              onClick={() => setTab(t.id as 'file' | 'paste' | 'study')}
              className={`flex-1 px-4 py-3 text-sm font-medium transition-colors ${
                tab === t.id
                  ? 'text-primary-400 border-b-2 border-primary-500 bg-dark-800'
                  : 'text-dark-400 hover:text-white hover:bg-dark-800'
              }`}
            >
              {t.label}
            </button>
          ))}
        </div>

        {/* Content */}
        <div className="p-6">
          {/* File Upload Tab */}
          {tab === 'file' && (
            <div className="space-y-4">
              <p className="text-sm text-dark-300">
                Upload an <code className="bg-dark-700 px-1 rounded text-primary-300">optimization_config.json</code> file
                from an existing study.
              </p>
              <input
                ref={fileInputRef}
                type="file"
                accept=".json"
                onChange={handleFileSelect}
                className="hidden"
              />
              <button
                onClick={() => fileInputRef.current?.click()}
                disabled={isLoading}
                className="w-full py-8 border-2 border-dashed border-dark-600 rounded-lg hover:border-primary-500/50 hover:bg-dark-800 transition-colors flex flex-col items-center gap-2"
              >
                <span className="text-3xl">📁</span>
                <span className="text-dark-300">
                  {isLoading ? 'Loading...' : 'Click to select file'}
                </span>
              </button>
            </div>
          )}

          {/* Paste JSON Tab */}
          {tab === 'paste' && (
            <div className="space-y-4">
              <p className="text-sm text-dark-300">
                Paste your optimization configuration JSON below.
              </p>
              <textarea
                value={jsonText}
                onChange={(e) => setJsonText(e.target.value)}
                placeholder={`{
  "design_variables": [...],
  "objectives": [...],
  "method": "TPE"
}`}
                className="w-full h-48 px-3 py-2 bg-dark-800 border border-dark-600 text-white placeholder-dark-500 rounded-lg font-mono text-sm focus:ring-2 focus:ring-primary-500 focus:border-primary-500 focus:outline-none transition-colors"
              />
              <button
                onClick={handlePasteImport}
                disabled={!jsonText.trim()}
                className="w-full px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                Import JSON
              </button>
            </div>
          )}

          {/* Load Study Tab */}
          {tab === 'study' && (
            <div className="space-y-4">
              <p className="text-sm text-dark-300">
                Enter a study name to load its configuration.
              </p>
              <input
                type="text"
                value={studyPath}
                onChange={(e) => setStudyPath(e.target.value)}
                placeholder="e.g., bracket_mass_v1 or M1_Mirror/m1_mirror_flatback"
                className="w-full px-3 py-2 bg-dark-800 border border-dark-600 text-white placeholder-dark-400 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500 focus:outline-none transition-colors"
              />
              <button
                onClick={handleStudyLoad}
                disabled={!studyPath.trim() || isLoading}
                className="w-full px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                {isLoading ? 'Loading...' : 'Load Study Config'}
              </button>
            </div>
          )}

          {/* Error Display */}
          {error && (
            <div className="mt-4 p-3 bg-red-900/30 border border-red-500/50 rounded-lg">
              <p className="text-sm text-red-400">{error}</p>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="px-6 py-4 border-t border-dark-700 bg-dark-800/50 rounded-b-xl">
          <p className="text-xs text-dark-500">
            Imported configurations will replace the current canvas content.
          </p>
        </div>
      </div>
    </div>
  );
}
