import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Card } from '../components/common/Card';
import { Input } from '../components/common/Input';
import { Button } from '../components/common/Button';
import { Plus, Trash2, Upload, Save } from 'lucide-react';
import { apiClient } from '../api/client';

interface DesignVariable {
  id: string;
  name: string;
  min: number;
  max: number;
  unit: string;
}

interface Objective {
  id: string;
  name: string;
  goal: 'minimize' | 'maximize' | 'target';
  target?: number;
  weight: number;
}

export default function Configurator() {
  const navigate = useNavigate();
  const [studyName, setStudyName] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [variables, setVariables] = useState<DesignVariable[]>([
    { id: '1', name: 'thickness', min: 2.0, max: 10.0, unit: 'mm' }
  ]);
  const [objectives, setObjectives] = useState<Objective[]>([
    { id: '1', name: 'mass', goal: 'minimize', weight: 1.0 }
  ]);

  const addVariable = () => {
    setVariables([
      ...variables,
      { id: Date.now().toString(), name: '', min: 0, max: 100, unit: '' }
    ]);
  };

  const removeVariable = (id: string) => {
    setVariables(variables.filter(v => v.id !== id));
  };

  const updateVariable = (id: string, field: keyof DesignVariable, value: any) => {
    setVariables(variables.map(v => 
      v.id === id ? { ...v, [field]: value } : v
    ));
  };

  const handleCreateStudy = async () => {
    if (!studyName) return;
    
    setIsSubmitting(true);
    try {
      const config = {
        name: studyName,
        design_variables: variables.map(({ id, ...v }) => v),
        objectives: objectives.map(({ id, ...o }) => o),
        optimization_settings: {
          n_trials: 50,
          sampler: 'tpe'
        }
      };
      
      await apiClient.createStudy(config);
      navigate('/dashboard');
    } catch (error) {
      console.error('Failed to create study:', error);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="container mx-auto max-w-5xl">
      <header className="mb-8 flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-primary-400">Study Configurator</h1>
          <p className="text-dark-300 mt-1">Create and configure new optimization studies</p>
        </div>
        <Button 
          icon={<Save className="w-4 h-4" />}
          onClick={handleCreateStudy}
          isLoading={isSubmitting}
          disabled={!studyName}
        >
          Create Study
        </Button>
      </header>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        {/* Left Column: Basic Info & Files */}
        <div className="space-y-6 lg:col-span-1">
          <Card title="Study Details">
            <div className="space-y-4">
              <Input
                label="Study Name"
                placeholder="e.g., bracket_optimization_v1"
                value={studyName}
                onChange={(e) => setStudyName(e.target.value)}
              />
              
              <div className="pt-4 border-t border-dark-600">
                <label className="block text-sm font-medium text-dark-200 mb-2">
                  Model Files
                </label>
                <div className="border-2 border-dashed border-dark-600 rounded-lg p-6 text-center hover:border-primary-500/50 hover:bg-dark-800/50 transition-colors cursor-pointer">
                  <Upload className="w-8 h-8 text-dark-400 mx-auto mb-2" />
                  <p className="text-sm text-dark-300">
                    Drag & drop .prt, .sim, .fem files here
                  </p>
                  <p className="text-xs text-dark-500 mt-1">
                    or click to browse
                  </p>
                </div>
              </div>
            </div>
          </Card>

          <Card title="Optimization Settings">
            <div className="space-y-4">
              <Input
                label="Number of Trials"
                type="number"
                defaultValue={50}
              />
              <div className="space-y-2">
                <label className="block text-sm font-medium text-dark-200">
                  Sampler
                </label>
                <select className="w-full bg-dark-800 border border-dark-600 rounded-lg px-3 py-2 text-dark-50 focus:outline-none focus:ring-2 focus:ring-primary-500">
                  <option value="tpe">TPE (Tree-structured Parzen Estimator)</option>
                  <option value="cmaes">CMA-ES</option>
                  <option value="random">Random Search</option>
                </select>
              </div>
            </div>
          </Card>
        </div>

        {/* Right Column: Variables & Objectives */}
        <div className="space-y-6 lg:col-span-2">
          <Card title="Design Variables">
            <div className="space-y-4">
              {variables.map((variable) => (
                <div key={variable.id} className="flex gap-3 items-start bg-dark-900/50 p-3 rounded-lg border border-dark-700">
                  <div className="flex-1 grid grid-cols-12 gap-3">
                    <div className="col-span-4">
                      <Input
                        placeholder="Name"
                        value={variable.name}
                        onChange={(e) => updateVariable(variable.id, 'name', e.target.value)}
                      />
                    </div>
                    <div className="col-span-3">
                      <Input
                        type="number"
                        placeholder="Min"
                        value={variable.min}
                        onChange={(e) => updateVariable(variable.id, 'min', parseFloat(e.target.value))}
                      />
                    </div>
                    <div className="col-span-3">
                      <Input
                        type="number"
                        placeholder="Max"
                        value={variable.max}
                        onChange={(e) => updateVariable(variable.id, 'max', parseFloat(e.target.value))}
                      />
                    </div>
                    <div className="col-span-2">
                      <Input
                        placeholder="Unit"
                        value={variable.unit}
                        onChange={(e) => updateVariable(variable.id, 'unit', e.target.value)}
                      />
                    </div>
                  </div>
                  <button
                    onClick={() => removeVariable(variable.id)}
                    className="p-2 text-dark-400 hover:text-red-400 hover:bg-dark-800 rounded-lg transition-colors mt-0.5"
                  >
                    <Trash2 className="w-4 h-4" />
                  </button>
                </div>
              ))}
              
              <Button
                variant="secondary"
                size="sm"
                className="w-full border-dashed"
                onClick={addVariable}
                icon={<Plus className="w-4 h-4" />}
              >
                Add Variable
              </Button>
            </div>
          </Card>

          <Card title="Objectives">
            <div className="space-y-4">
              {objectives.map((objective) => (
                <div key={objective.id} className="flex gap-3 items-start bg-dark-900/50 p-3 rounded-lg border border-dark-700">
                  <div className="flex-1 grid grid-cols-12 gap-3">
                    <div className="col-span-5">
                      <Input
                        placeholder="Name (e.g., mass, stress)"
                        value={objective.name}
                        onChange={(e) => {
                          const newObjectives = objectives.map(o => 
                            o.id === objective.id ? { ...o, name: e.target.value } : o
                          );
                          setObjectives(newObjectives);
                        }}
                      />
                    </div>
                    <div className="col-span-4">
                      <select 
                        className="w-full bg-dark-800 border border-dark-600 rounded-lg px-3 py-2 text-dark-50 focus:outline-none focus:ring-2 focus:ring-primary-500"
                        value={objective.goal}
                        onChange={(e) => {
                          const newObjectives = objectives.map(o => 
                            o.id === objective.id ? { ...o, goal: e.target.value as any } : o
                          );
                          setObjectives(newObjectives);
                        }}
                      >
                        <option value="minimize">Minimize</option>
                        <option value="maximize">Maximize</option>
                        <option value="target">Target Value</option>
                      </select>
                    </div>
                    <div className="col-span-3">
                      <Input
                        type="number"
                        placeholder="Weight"
                        value={objective.weight}
                        onChange={(e) => {
                          const newObjectives = objectives.map(o => 
                            o.id === objective.id ? { ...o, weight: parseFloat(e.target.value) } : o
                          );
                          setObjectives(newObjectives);
                        }}
                      />
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}