import { useState } from 'react';
import { Radio, Space, Input, Button, Tag, Tooltip, Slider, Typography } from 'antd';
import { InfoCircleOutlined, PlusOutlined } from '@ant-design/icons';
import type { CategoryDefinition, CategoryMode, Step0Result } from '../types';

const { Text } = Typography;

interface CategorySelectorProps {
  mode: CategoryMode;
  onModeChange: (mode: CategoryMode) => void;
  customCategories: string[];
  onCustomCategoriesChange: (cats: string[]) => void;
  suggestedCount: number;
  onSuggestedCountChange: (count: number) => void;
  step0Result?: Step0Result;
  onStep0Edit?: (cats: CategoryDefinition[]) => void;
  disabled?: boolean;
}

export function CategorySelector({
  mode,
  onModeChange,
  customCategories,
  onCustomCategoriesChange,
  suggestedCount,
  onSuggestedCountChange,
  step0Result,
  onStep0Edit,
  disabled
}: CategorySelectorProps) {
  const [inputValue, setInputValue] = useState('');

  return (
    <Space direction="vertical" style={{ width: '100%' }}>
      <Radio.Group
        value={mode}
        onChange={(e) => onModeChange(e.target.value as CategoryMode)}
        disabled={disabled}
      >
        <Space direction="vertical">
          <Radio value="fixed_only">
            Fixed (材料、功能、用途、使用族群)
          </Radio>
          <Radio value="fixed_plus_custom">
            Fixed + Custom (手動新增)
          </Radio>
          <Radio value="fixed_plus_dynamic">
            Fixed + Dynamic (LLM 建議額外類別)
          </Radio>
          <Radio value="custom_only">
            Custom Only (LLM 建議)
          </Radio>
          <Radio value="dynamic_auto">
            Dynamic (LLM 建議, 可編輯)
          </Radio>
        </Space>
      </Radio.Group>

      {/* 動態模式：類別數量調整 */}
      {(mode === 'custom_only' || mode === 'dynamic_auto' || mode === 'fixed_plus_dynamic') && (
        <div>
          <Text>
            {mode === 'fixed_plus_dynamic'
              ? `額外建議類別數: ${suggestedCount}`
              : `Suggested Category Count: ${suggestedCount}`}
          </Text>
          <Slider
            min={1}
            max={mode === 'fixed_plus_dynamic' ? 4 : 8}
            step={1}
            value={suggestedCount}
            onChange={onSuggestedCountChange}
            marks={mode === 'fixed_plus_dynamic'
              ? { 1: '1', 2: '2', 3: '3', 4: '4' }
              : { 2: '2', 3: '3', 5: '5', 8: '8' }}
            disabled={disabled}
          />
        </div>
      )}

      {/* 固定+自定義模式 */}
      {mode === 'fixed_plus_custom' && (
        <div>
          <Text type="secondary">Add custom categories:</Text>
          <Space.Compact style={{ width: '100%', marginTop: 8 }}>
            <Input
              placeholder="Category name"
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              onPressEnter={() => {
                if (inputValue.trim()) {
                  onCustomCategoriesChange([...customCategories, inputValue.trim()]);
                  setInputValue('');
                }
              }}
              disabled={disabled}
            />
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => {
                if (inputValue.trim()) {
                  onCustomCategoriesChange([...customCategories, inputValue.trim()]);
                  setInputValue('');
                }
              }}
              disabled={disabled}
            >
              Add
            </Button>
          </Space.Compact>

          {customCategories.length > 0 && (
            <div style={{ marginTop: 8 }}>
              {customCategories.map((cat, i) => (
                <Tag
                  key={i}
                  closable
                  onClose={() => {
                    onCustomCategoriesChange(customCategories.filter((_, idx) => idx !== i));
                  }}
                >
                  {cat}
                </Tag>
              ))}
            </div>
          )}
        </div>
      )}

      {/* Step 0 結果顯示 */}
      {step0Result && (mode === 'custom_only' || mode === 'dynamic_auto' || mode === 'fixed_plus_dynamic') && (
        <div style={{ marginTop: 8, padding: 12, background: 'rgba(0,0,0,0.04)', borderRadius: 4 }}>
          <Text strong>LLM Suggested:</Text>
          <div style={{ marginTop: 8 }}>
            {step0Result.categories.map((cat, i) => (
              <Tag
                key={i}
                color="blue"
                closable={mode === 'dynamic_auto'}
                onClose={mode === 'dynamic_auto' ? () => {
                  if (onStep0Edit) {
                    onStep0Edit(step0Result.categories.filter((_, idx) => idx !== i));
                  }
                } : undefined}
              >
                {cat.name}
                {cat.description && (
                  <Tooltip title={cat.description}>
                    <InfoCircleOutlined style={{ marginLeft: 4 }} />
                  </Tooltip>
                )}
              </Tag>
            ))}
          </div>

          {mode === 'dynamic_auto' && (
            <Text type="secondary" style={{ fontSize: 12, marginTop: 8, display: 'block' }}>
              You can remove tags or proceed
            </Text>
          )}
        </div>
      )}
    </Space>
  );
}
