import { useState, useEffect } from 'react';
import {
  Input,
  Button,
  Select,
  Typography,
  Space,
  message,
  Slider,
  Collapse,
  Progress,
  Card,
  Alert,
  Tag,
  Divider,
} from 'antd';
import {
  SearchOutlined,
  LoadingOutlined,
  SwapOutlined,
} from '@ant-design/icons';
import type { CategoryMode, DAGProgress, PromptLanguage } from '../types';
import { getModels } from '../services/api';
import { CategorySelector } from './CategorySelector';

const { TextArea } = Input;
const { Text } = Typography;

interface DualPathInputPanelProps {
  onAnalyze: (queryA: string, queryB: string, options?: {
    model?: string;
    temperature?: number;
    chainCount?: number;
    categoryMode?: CategoryMode;
    customCategories?: string[];
    suggestedCategoryCount?: number;
    lang?: PromptLanguage;
  }) => Promise<void>;
  loadingA: boolean;
  loadingB: boolean;
  progressA: DAGProgress;
  progressB: DAGProgress;
  availableModels?: string[];
  lang?: PromptLanguage;
}

export function DualPathInputPanel({
  onAnalyze,
  loadingA,
  loadingB,
  progressA,
  progressB,
  availableModels: propModels,
  lang = 'zh',
}: DualPathInputPanelProps) {
  const [queryA, setQueryA] = useState('');
  const [queryB, setQueryB] = useState('');
  const [models, setModels] = useState<string[]>(propModels || []);
  const [selectedModel, setSelectedModel] = useState<string | undefined>();
  const [loadingModels, setLoadingModels] = useState(false);
  const [temperature, setTemperature] = useState(0.7);
  const [chainCount, setChainCount] = useState(5);
  // Category settings
  const [categoryMode, setCategoryMode] = useState<CategoryMode>('dynamic_auto' as CategoryMode);
  const [customCategories, setCustomCategories] = useState<string[]>([]);
  const [suggestedCategoryCount, setSuggestedCategoryCount] = useState(3);

  const isLoading = loadingA || loadingB;

  useEffect(() => {
    if (propModels && propModels.length > 0) {
      setModels(propModels);
      if (!selectedModel) {
        const defaultModel = propModels.find((m) => m.includes('qwen3')) || propModels[0];
        setSelectedModel(defaultModel);
      }
      return;
    }

    async function fetchModels() {
      setLoadingModels(true);
      try {
        const response = await getModels();
        setModels(response.models);
        if (response.models.length > 0 && !selectedModel) {
          const defaultModel = response.models.find((m) => m.includes('qwen3')) || response.models[0];
          setSelectedModel(defaultModel);
        }
      } catch {
        message.error('Failed to fetch models');
      } finally {
        setLoadingModels(false);
      }
    }

    fetchModels();
  }, [propModels]);

  const handleAnalyze = async () => {
    if (!queryA.trim() || !queryB.trim()) {
      message.warning(lang === 'zh' ? '請輸入兩個路徑的查詢內容' : 'Please enter queries for both paths');
      return;
    }

    try {
      await onAnalyze(queryA.trim(), queryB.trim(), {
        model: selectedModel,
        temperature,
        chainCount,
        categoryMode,
        customCategories: customCategories.length > 0 ? customCategories : undefined,
        suggestedCategoryCount,
        lang,
      });
    } catch {
      message.error(lang === 'zh' ? '分析失敗' : 'Analysis failed');
    }
  };

  const handleSwapQueries = () => {
    const temp = queryA;
    setQueryA(queryB);
    setQueryB(temp);
  };

  const renderProgressIndicator = (label: string, progress: DAGProgress, loading: boolean) => {
    if (progress.step === 'idle' && !loading) return null;
    if (progress.step === 'done') return null;

    const percent = progress.step === 'step0'
      ? 15
      : progress.step === 'step1'
        ? 50
        : progress.step === 'relationships'
          ? 85
          : 100;

    return (
      <div style={{ marginTop: 8 }}>
        <Text type="secondary" style={{ fontSize: 12 }}>{label}: {progress.message}</Text>
        <Progress
          percent={Math.round(percent)}
          size="small"
          status={progress.step === 'error' ? 'exception' : 'active'}
          strokeColor={{ from: '#108ee9', to: '#87d068' }}
        />
      </div>
    );
  };

  const collapseItems = [
    {
      key: 'categories',
      label: 'Category Settings',
      children: (
        <CategorySelector
          mode={categoryMode}
          onModeChange={setCategoryMode}
          customCategories={customCategories}
          onCustomCategoriesChange={setCustomCategories}
          suggestedCount={suggestedCategoryCount}
          onSuggestedCountChange={setSuggestedCategoryCount}
          disabled={isLoading}
        />
      ),
    },
    {
      key: 'llm',
      label: 'LLM Parameters',
      children: (
        <Space direction="vertical" style={{ width: '100%' }} size="middle">
          <div>
            <Text type="secondary" style={{ fontSize: 12 }}>Temperature: {temperature}</Text>
            <Slider
              min={0}
              max={1}
              step={0.1}
              value={temperature}
              onChange={setTemperature}
              marks={{ 0: '0', 0.5: '0.5', 1: '1' }}
              disabled={isLoading}
            />
          </div>
          <div>
            <Text type="secondary" style={{ fontSize: 12 }}>Chain Count: {chainCount}</Text>
            <Slider
              min={1}
              max={10}
              step={1}
              value={chainCount}
              onChange={setChainCount}
              marks={{ 1: '1', 5: '5', 10: '10' }}
              disabled={isLoading}
            />
          </div>
        </Space>
      ),
    },
  ];

  return (
    <div style={{
      display: 'flex',
      flexDirection: 'column',
      height: '100%',
      padding: 16,
      gap: 16,
    }}>
      {/* Dual Path Input Card */}
      <Card
        size="small"
        title={<Text strong>Dual Path Analysis</Text>}
        styles={{ body: { padding: 12 } }}
      >
        <Space direction="vertical" style={{ width: '100%' }} size="middle">
          {/* Model Selection */}
          <Select
            style={{ width: '100%' }}
            value={selectedModel}
            onChange={setSelectedModel}
            loading={loadingModels}
            placeholder="Select a model"
            options={models.map((m) => ({ label: m, value: m }))}
            size="middle"
            disabled={isLoading}
          />

          {/* Path A Input */}
          <div>
            <Tag color="blue" style={{ marginBottom: 4 }}>Path A</Tag>
            <TextArea
              value={queryA}
              onChange={(e) => setQueryA(e.target.value)}
              placeholder="Enter first object (e.g., umbrella)"
              autoSize={{ minRows: 1, maxRows: 2 }}
              disabled={isLoading}
            />
            {renderProgressIndicator('Path A', progressA, loadingA)}
          </div>

          {/* Swap Button */}
          <div style={{ textAlign: 'center' }}>
            <Button
              icon={<SwapOutlined rotate={90} />}
              size="small"
              onClick={handleSwapQueries}
              disabled={isLoading}
            >
              Swap
            </Button>
          </div>

          {/* Path B Input */}
          <div>
            <Tag color="green" style={{ marginBottom: 4 }}>Path B</Tag>
            <TextArea
              value={queryB}
              onChange={(e) => setQueryB(e.target.value)}
              placeholder="Enter second object (e.g., bicycle)"
              autoSize={{ minRows: 1, maxRows: 2 }}
              disabled={isLoading}
            />
            {renderProgressIndicator('Path B', progressB, loadingB)}
          </div>

          {/* Analyze Button */}
          <Button
            type="primary"
            icon={<SearchOutlined />}
            onClick={handleAnalyze}
            loading={isLoading}
            block
            size="large"
            disabled={!queryA.trim() || !queryB.trim()}
          >
            {isLoading ? 'Analyzing...' : 'Analyze Both'}
          </Button>
        </Space>
      </Card>

      {/* Combined Progress Alert */}
      {isLoading && (
        <Alert
          type="info"
          icon={<LoadingOutlined spin />}
          message="Parallel Analysis in Progress"
          description={
            <Space direction="vertical" style={{ width: '100%' }}>
              <div>
                <Tag color="blue">A</Tag> {progressA.message || 'Waiting...'}
              </div>
              <div>
                <Tag color="green">B</Tag> {progressB.message || 'Waiting...'}
              </div>
            </Space>
          }
          showIcon
        />
      )}

      <Divider style={{ margin: '4px 0' }} />

      {/* Settings Collapse */}
      <Collapse
        items={collapseItems}
        defaultActiveKey={[]}
        size="small"
        style={{ background: 'transparent' }}
      />
    </div>
  );
}
