'use client';

import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Brain,
  ChevronDown,
  Zap,
  Clock,
  Star,
  X,
  Check,
  RotateCcw,
} from 'lucide-react';
import {
  LLM_MODELS,
  DEFAULT_STAGE_CONFIG,
  STAGE_INFO,
  LLMStageConfig,
  LLMModelOption,
  PipelineStage,
} from '@/lib/dark-factory/llm-models';

interface LLMSelectorProps {
  config: LLMStageConfig;
  onChange: (config: LLMStageConfig) => void;
  disabled?: boolean;
}

const SPEED_ICONS = {
  fast: <Zap className="w-3 h-3 text-green-400" />,
  medium: <Clock className="w-3 h-3 text-yellow-400" />,
  slow: <Clock className="w-3 h-3 text-orange-400" />,
};

const QUALITY_STARS = {
  good: 1,
  great: 2,
  best: 3,
};

export function LLMSelector({ config, onChange, disabled }: LLMSelectorProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [activeStage, setActiveStage] = useState<PipelineStage>('architecture');

  const isDefault = JSON.stringify(config) === JSON.stringify(DEFAULT_STAGE_CONFIG);

  const handleModelSelect = (stage: PipelineStage, modelId: string) => {
    onChange({ ...config, [stage]: modelId });
  };

  const handleReset = () => {
    onChange({ ...DEFAULT_STAGE_CONFIG });
  };

  // Get a compact summary of the current config
  const getSummary = () => {
    const uniqueModels = new Set(Object.values(config));
    if (uniqueModels.size === 1) {
      const model = LLM_MODELS.find(m => m.id === [...uniqueModels][0]);
      return model ? `${model.icon} ${model.name} (all stages)` : 'Custom';
    }
    return `${uniqueModels.size} models configured`;
  };

  return (
    <div className="relative">
      {/* Compact trigger */}
      <button
        type="button"
        onClick={() => setIsOpen(!isOpen)}
        disabled={disabled}
        className={`flex items-center gap-2 px-3 py-2 rounded-lg text-sm transition-all border ${
          !isDefault
            ? 'bg-brand-secondary/15 border-brand-secondary/40 text-brand-secondary-light'
            : 'bg-white/5 border-white/10 text-gray-400 hover:text-white hover:border-white/20'
        } disabled:opacity-50 disabled:cursor-not-allowed`}
      >
        <Brain className="w-4 h-4" />
        <span className="hidden sm:inline">LLM:</span>
        <span className="text-xs truncate max-w-[120px]">{getSummary()}</span>
        <ChevronDown className={`w-3.5 h-3.5 transition-transform ${isOpen ? 'rotate-180' : ''}`} />
      </button>

      {/* Dropdown panel */}
      <AnimatePresence>
        {isOpen && (
          <motion.div
            initial={{ opacity: 0, y: -5, scale: 0.98 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: -5, scale: 0.98 }}
            className="absolute z-50 right-0 top-full mt-2 w-[460px] max-h-[500px] overflow-hidden rounded-xl bg-brand-bg-elevated border border-brand-secondary/30 shadow-2xl"
          >
            {/* Header */}
            <div className="flex items-center justify-between px-4 py-3 border-b border-white/10">
              <div className="flex items-center gap-2">
                <Brain className="w-5 h-5 text-brand-secondary-light" />
                <span className="font-medium text-white">Multi-LLM Configuration</span>
              </div>
              <div className="flex items-center gap-2">
                {!isDefault && (
                  <button
                    onClick={handleReset}
                    className="flex items-center gap-1 px-2 py-1 rounded text-xs text-gray-400 hover:text-white hover:bg-white/10 transition-colors"
                  >
                    <RotateCcw className="w-3 h-3" />
                    Reset
                  </button>
                )}
                <button
                  onClick={() => setIsOpen(false)}
                  className="p-1 rounded hover:bg-white/10 transition-colors"
                >
                  <X className="w-4 h-4 text-gray-400" />
                </button>
              </div>
            </div>

            {/* Stage tabs */}
            <div className="flex border-b border-white/10">
              {(Object.keys(STAGE_INFO) as PipelineStage[]).map((stage) => (
                <button
                  key={stage}
                  onClick={() => setActiveStage(stage)}
                  className={`flex-1 px-3 py-2.5 text-center text-xs font-medium transition-all border-b-2 ${
                    activeStage === stage
                      ? 'border-brand-secondary-light text-brand-secondary-light bg-brand-secondary/10'
                      : 'border-transparent text-gray-500 hover:text-gray-300'
                  }`}
                >
                  <span className="block">{STAGE_INFO[stage].icon}</span>
                  <span className="block mt-0.5">{STAGE_INFO[stage].label.split(' ')[0]}</span>
                </button>
              ))}
            </div>

            {/* Stage description */}
            <div className="px-4 py-2 bg-white/5 text-xs text-gray-400">
              {STAGE_INFO[activeStage].description}
            </div>

            {/* Model list */}
            <div className="overflow-y-auto max-h-[300px] p-2">
              {LLM_MODELS.map((model) => (
                <ModelRow
                  key={model.id}
                  model={model}
                  isSelected={config[activeStage] === model.id}
                  onSelect={() => handleModelSelect(activeStage, model.id)}
                />
              ))}
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}

function ModelRow({
  model,
  isSelected,
  onSelect,
}: {
  model: LLMModelOption;
  isSelected: boolean;
  onSelect: () => void;
}) {
  return (
    <button
      onClick={onSelect}
      className={`w-full flex items-center gap-3 p-3 rounded-lg text-left transition-all ${
        isSelected
          ? 'bg-brand-secondary/15 border border-brand-secondary/30'
          : 'hover:bg-white/5 border border-transparent'
      }`}
    >
      <span className="text-xl flex-shrink-0">{model.icon}</span>
      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-2">
          <span className={`text-sm font-medium ${isSelected ? 'text-brand-secondary-light' : 'text-white'}`}>
            {model.name}
          </span>
          {isSelected && <Check className="w-3.5 h-3.5 text-brand-secondary-light" />}
        </div>
        <p className="text-xs text-gray-500 mt-0.5 truncate">{model.description}</p>
        <div className="flex items-center gap-3 mt-1">
          <span className="flex items-center gap-1 text-xs text-gray-500">
            {SPEED_ICONS[model.speed]}
            {model.speed}
          </span>
          <span className="flex items-center gap-0.5 text-xs text-gray-500">
            {Array.from({ length: QUALITY_STARS[model.quality] }).map((_, i) => (
              <Star key={i} className="w-2.5 h-2.5 text-yellow-400 fill-yellow-400" />
            ))}
          </span>
          <span className={`text-xs px-1.5 py-0.5 rounded ${
            model.costTier === 'low' ? 'bg-green-500/10 text-green-400' :
            model.costTier === 'medium' ? 'bg-yellow-500/10 text-yellow-400' :
            'bg-red-500/10 text-red-400'
          }`}>
            ${model.costTier}
          </span>
        </div>
      </div>
    </button>
  );
}
