import { useMemo, useEffect, useState } from 'react';
import {
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  FormHelperText,
  Box,
  Typography,
  ListSubheader,
  Button,
} from '@mui/material';
import { Shuffle as ShuffleIcon } from '@mui/icons-material';
import { useFormContext, Controller } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { t as translate } from 'i18next';
import { DocumentParserType, LlmModelType } from '@/constants/knowledge';
import { AgentCategory } from '@/constants/agent';
import { useSelectChunkMethodList } from '../hooks';
import { useEmbeddingModelOptions, useLlmOptionsByModelType } from '@/hooks/llm-hooks';
import {
  SliderInputFormField,
  SwitchFormField,
  SelectFormField,
  MultilineTextFormField,
  NumberInputFormField,
  ChipListFormField,
  TextFormField,
  type SelectOption,
} from '@/components/FormField';
import agentService from '@/services/agent_service';
import { LlmSvgIcon } from '@/components/AppSvgIcon';
import {type LLMFactory } from '@/constants/llm';
import { getFactoryIconName } from '@/utils/common';

// 解析器选项配置
const PARSER_OPTIONS = [
  { value: DocumentParserType.Naive, label: 'General', description: translate('knowledge.config.parser.general') },
  { value: DocumentParserType.Qa, label: 'Q&A', description: translate('knowledge.config.parser.qa') },
  { value: DocumentParserType.Resume, label: 'Resume', description: translate('knowledge.config.parser.resume') },
  { value: DocumentParserType.Manual, label: 'Manual', description: translate('knowledge.config.parser.manual') },
  { value: DocumentParserType.Table, label: 'Table', description: translate('knowledge.config.parser.table') },
  { value: DocumentParserType.Paper, label: 'Paper', description: translate('knowledge.config.parser.paper') },
  { value: DocumentParserType.Book, label: 'Book', description: translate('knowledge.config.parser.book') },
  { value: DocumentParserType.Laws, label: 'Laws', description: translate('knowledge.config.parser.laws') },
  { value: DocumentParserType.Presentation, label: 'Presentation', description: translate('knowledge.config.parser.presentation') },
  { value: DocumentParserType.One, label: 'One', description: translate('knowledge.config.parser.one') },
  { value: DocumentParserType.Tag, label: 'Tag', description: translate('knowledge.config.parser.tag') },
];

/* ============================================================================
 * 第一部分：基础配置 (Basic Configuration)
 * ============================================================================ */

/**
 * 嵌入模型选择
 */
export function EmbeddingModelItem() {
  const { control } = useFormContext();
  const { t } = useTranslation();
  const { options } = useEmbeddingModelOptions();

  return (
    <Box>
      <Typography variant="subtitle1" sx={{ minWidth: 120 }}>
        {t('knowledge.config.embeddingModel')}
      </Typography>
      <Box sx={{ flex: 1 }}>
        <Controller
          name="embd_id"
          control={control}
          render={({ field }) => (
            <FormControl fullWidth variant="outlined">
              <Select
                {...field}
              >
                {options.map((group) => [
                  <ListSubheader key={group.label}>{group.label}</ListSubheader>,
                  ...group.options.map((option) => (
                    <MenuItem key={option.value} value={option.value} disabled={option.disabled}>
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                        <LlmSvgIcon
                          name={getFactoryIconName(group.label as LLMFactory)}
                          sx={{ width: 20, height: 20, color: 'primary.main' }}
                        />
                        {option.label}
                      </Box>
                    </MenuItem>
                  ))
                ])}
              </Select>
            </FormControl>
          )}
        />
      </Box>
    </Box>
  );
}

/**
 * 分块方法选择
 */
export function ChunkMethodItem() {
  const { control, formState: { errors } } = useFormContext();
  const parserIds = useSelectChunkMethodList();

  const {t} = useTranslation();

  const parserOptions = parserIds.map((x) => {
    const parserOption = PARSER_OPTIONS.find((y) => y.value === x);
    return {
      value: x,
      label: parserOption?.label || x,
      description: parserOption?.description || x,
    };
  });

  return (
    <Box>
      <Typography variant="h6" gutterBottom>
        {t('knowledge.config.chunkMethod')}
      </Typography>
      <Controller
        name="parser_id"
        control={control}
        render={({ field }) => (
          <FormControl fullWidth error={!!errors.parser_id}>
            <InputLabel>{t('knowledge.config.selectChunkMethod')}</InputLabel>
            <Select
              {...field}
              label={t('knowledge.config.selectChunkMethod')}
            >
              {parserOptions.map((option) => (
                <MenuItem key={option.value} value={option.value}>
                  <Box>
                    <Typography variant="body1">{option.label}</Typography>
                    <Typography variant="caption" color="text.secondary">
                      {option.description}
                    </Typography>
                  </Box>
                </MenuItem>
              ))}
            </Select>
            {errors.parser_id && (
              <FormHelperText>{errors.parser_id.message as string}</FormHelperText>
            )}
          </FormControl>
        )}
      />
    </Box>
  );
}

// 标签集选择
export function TagsItem() {
  const { t } = useTranslation();
  const tagsOptions: SelectOption[] = [
    // 这里可以根据实际需求添加标签选项
  ];

  return (
    <SelectFormField
      name="parser_config.tags"
      label={t('knowledge.config.tags')}
      options={tagsOptions}
      displayEmpty={false}
    />
  );
}

// 页面排名配置
export function PageRankItem() {
  const { t } = useTranslation();
  return (
    <NumberInputFormField
      name="pagerank"
      label={t('knowledge.config.pageRank')}
      defaultValue={0}
      min={0}
      placeholder={t('knowledge.config.enterPageRank')}
    />
  );
}

// PDF解析器配置
export function LayoutRecognizeItem() {
  const { control, setValue, formState } = useFormContext();
  const { t } = useTranslation();
  const { getOptionsByModelType } = useLlmOptionsByModelType();

  const { basicOptions, image2TextOptions } = useMemo(() => {
    // 基础选项
    const basicOptions = [
      { value: 'DeepDOC', label: 'DeepDOC' },
      { value: 'Plain Text', label: t('knowledge.config.plainText') },
      { value: 'MinerU', label: t('knowledge.config.minerU') }
    ];

    // 获取图像转文本模型选项
    const image2TextOptions = getOptionsByModelType(LlmModelType.Image2text);

    return { basicOptions, image2TextOptions };
  }, [getOptionsByModelType, t]);

  return (
    <Box>
      <Typography variant="subtitle1" sx={{ minWidth: 120 }}>
        {t('knowledge.config.pdfParser')}
      </Typography>
      <Box sx={{ flex: 1 }}>
        <Controller
          name="parser_config.layout_recognize"
          control={control}
          render={({ field }) => {
            // 设置默认值
            if (typeof field.value === 'undefined') {
              const defaultValue = formState.defaultValues?.parser_config?.layout_recognize ?? 'DeepDOC';
              setValue('parser_config.layout_recognize', defaultValue);
            }

            return (
              <FormControl fullWidth variant="outlined">
                <Select {...field}>
                  {/* 基础选项 */}
                  {basicOptions.map((option) => (
                    <MenuItem key={option.value} value={option.value}>
                      {option.label}
                    </MenuItem>
                  ))}
                  
                  {/* 图像转文本模型选项 - 带分组和图标 */}
                  {image2TextOptions.map((group) => [
                    <ListSubheader key={group.label}>{group.label}</ListSubheader>,
                    ...group.options.map((option) => (
                      <MenuItem key={option.value} value={option.value} disabled={option.disabled}>
                        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                          <LlmSvgIcon
                            name={getFactoryIconName(group.label as LLMFactory)}
                            sx={{ width: 20, height: 20, color: 'primary.main' }}
                          />
                          {option.label} 
                          <Typography variant="caption" color="error.main">
                            {t('knowledge.config.experimental')}
                          </Typography>
                        </Box>
                      </MenuItem>
                    ))
                  ])}
                </Select>
              </FormControl>
            );
          }}
        />
      </Box>
    </Box>
  );
}

// 文本分段标识符配置
export function DelimiterItem() {
  const { t } = useTranslation();
  return (
    <TextFormField
      name="parser_config.delimiter"
      label={t('knowledge.config.delimiter')}
      placeholder={t('knowledge.config.enterDelimiter')}
      defaultValue="\n"
    />
  );
}

// 分块token数量配置
export function ChunkTokenNumberItem() {
  const { t } = useTranslation();
  return (
    <SliderInputFormField
      name="parser_config.chunk_token_num"
      label={t('knowledge.config.chunkTokenSize')}
      min={64}
      max={2048}
      step={64}
      defaultValue={512}
      layout="horizontal"
    />
  );
}

// 自动关键词数量配置
export function AutoKeywordsItem() {
  const { t } = useTranslation();
  return (
    <SliderInputFormField
      name="parser_config.auto_keywords"
      label={t('knowledge.config.autoKeywords')}
      defaultValue={0}
      step={1}
      max={30}
      min={0}
    />
  );
}

// 自动问题数量配置
export function AutoQuestionsItem() {
  const { t } = useTranslation();
  return (
    <SliderInputFormField
      name="parser_config.auto_questions"
      label={t('knowledge.config.autoQuestions')}
      defaultValue={0}
      step={1}
      max={30}
      min={0}
    />
  );
}

// 表格转HTML开关
export function HtmlForExcelItem() {
  const { t } = useTranslation();
  return (
    <SwitchFormField
      name="parser_config.html4excel"
      label={t('knowledge.config.htmlForExcel')}
      defaultValue={false}
    />
  );
}

/**
 * 目录增强开关
 */
export function TOCEnhanceItem() {
  const { t } = useTranslation();
  return (
    <SwitchFormField
      name="parser_config.toc_extraction"
      label={t('knowledge.config.tocEnhance')}
      defaultValue={false}
    />
  );
}

// Pipeline 选择器
export function PipelineSelectorItem() {
  const { t } = useTranslation();
  const [options, setOptions] = useState<SelectOption[]>([]);

  useEffect(() => {
    const fetchPipelines = async () => {
      try {
        const envMode = import.meta.env.MODE;
        // const service = envMode === 'flask' ? agentService.teamlistCanvas : agentService.listCanvas;
        const service = agentService.listCanvas;
        const res = await service({ canvas_category: AgentCategory.DataflowCanvas, page_size: 100 });
        const data = res?.data?.data || {};
        const list = data.canvas || [];
        const mapped: SelectOption[] = list.map((item: any) => ({
          value: item.id,
          label: item.title || item.name || item.id,
          disabled: false,
        }));
        setOptions(mapped);
      } catch (err) {
        console.error('Failed to fetch pipelines:', err);
      }
    };
    fetchPipelines();
  }, []);

  return (
    <SelectFormField
      name="pipeline_id"
      label={t('knowledgeConfiguration.dataFlow')}
      options={options}
      displayEmpty={false}
    />
  );
}

/* ============================================================================
 * 第二部分：RAPTOR策略 (RAPTOR Strategy)
 * ============================================================================ */

// RAPTOR策略开关
export function UseRaptorItem() {
  const { t } = useTranslation();
  return (
    <SwitchFormField
      name="parser_config.raptor.use_raptor"
      label={t('knowledge.config.useRaptorStrategy')}
      defaultValue={false}
    />
  );
}

// RAPTOR提示词配置
export function RaptorPromptItem() {
  const { t } = useTranslation();
  return (
    <MultilineTextFormField
      name="parser_config.raptor.prompt"
      label={t('knowledge.config.prompt')}
      defaultValue={t('knowledge.config.raptorPromptDefault')}
      rows={4}
    />
  );
}

// RAPTOR最大token数配置
export function RaptorMaxTokenItem() {
  const { t } = useTranslation();
  return (
    <SliderInputFormField
      name="parser_config.raptor.max_token"
      label={t('knowledge.config.maxTokens')}
      min={64}
      max={2048}
      step={32}
      defaultValue={256}
      layout="horizontal"
    />
  );
}

// RAPTOR阈值配置
export function RaptorThresholdItem() {
  const { t } = useTranslation();
  return (
    <SliderInputFormField
      name="parser_config.raptor.threshold"
      label={t('knowledge.config.threshold')}
      min={0}
      max={1}
      step={0.1}
      defaultValue={0.1}
      layout="horizontal"
    />
  );
}

// RAPTOR最大聚类数配置
export function RaptorMaxClusterItem() {
  const { t } = useTranslation();
  return (
    <SliderInputFormField
      name="parser_config.raptor.max_cluster"
      label={t('knowledge.config.maxClusterCount')}
      min={16}
      max={1024}
      step={16}
      defaultValue={64}
      layout="horizontal"
    />
  );
}

// RAPTOR随机种子配置
export function RaptorRandomSeedItem() {
  const { t } = useTranslation();
  return (
    <NumberInputFormField
      name="parser_config.raptor.random_seed"
      label={t('knowledge.config.randomSeed')}
      defaultValue={0}
      showRandomButton
    />
  );
}

/* ============================================================================
 * 第三部分：知识图谱 (Knowledge Graph)
 * ============================================================================ */

// 知识图谱开关
export function UseGraphragItem() {
  const { t } = useTranslation();
  return (
    <SwitchFormField
      name="parser_config.graphrag.use_graphrag"
      label={t('knowledge.config.extractKnowledgeGraph')}
      defaultValue={false}
    />
  );
}

// 实体类型配置
export function EntityTypesItem() {
  const { t } = useTranslation();
  return (
    <ChipListFormField
      name="parser_config.graphrag.entity_types"
      label={t('knowledge.config.entityTypes')}
      defaultValue={['organization', 'person', 'geo', 'event', 'category']}
      required
      allowAdd
      allowDelete
      maxChips={10}
    />
  );
}

// GraphRAG方法选择
export function GraphragMethodItem() {
  const { t } = useTranslation();
  const methodOptions: SelectOption[] = [
    { value: 'Light', label: 'Light' },
    { value: 'General', label: 'General' },
  ];

  return (
    <SelectFormField
      name="parser_config.graphrag.method"
      label={t('knowledge.config.method')}
      options={methodOptions}
      defaultValue="Light"
      displayEmpty={false}
    />
  );
}

// 实体归一化开关
export function EntityNormalizeItem() {
  const { t } = useTranslation();
  return (
    <SwitchFormField
      name="parser_config.graphrag.entity_normalize"
      label={t('knowledge.config.entityNormalization')}
      defaultValue={false}
    />
  );
}

// 社区报告生成开关
export function CommunityReportItem() {
  const { t } = useTranslation();
  return (
    <SwitchFormField
      name="parser_config.graphrag.community_report"
      label={t('knowledge.config.communityReportGeneration')}
      defaultValue={false}
    />
  );
}

/* ============================================================================
 * 组合配置组件 (Composite Configuration Components)
 * ============================================================================ */

/* 
 * 基础配置项 (Basic Configuration Items)
 */
export function BasicConfigItems() {
  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
      {/* PDF解析器 */}
      <LayoutRecognizeItem />
      {/* 建议文本块大小 */}
      <ChunkTokenNumberItem />
      {/* 文本分段标识符 */}
      <DelimiterItem />
      {/* 目录增强 */}
      <TOCEnhanceItem />
      {/* 自动关键词提取 */}
      <AutoKeywordsItem />
      {/* 自动问题提取 */}
      <AutoQuestionsItem />
      {/* 表格转HTML */}
      <HtmlForExcelItem />
    </Box>
  );
}

/**
 * RAPTOR策略配置项组合
 */
export function RaptorConfigItems() {
  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
      {/* 使用召回增强RAPTOR策略 */}
      <UseRaptorItem />
      {/* 提示词 */}
      <RaptorPromptItem />
      {/* 最大token数 */}
      <RaptorMaxTokenItem />
      {/* 阈值 */}
      <RaptorThresholdItem />
      {/* 最大聚类数 */}
      <RaptorMaxClusterItem />
      {/* 随机种子 */}
      <RaptorRandomSeedItem />
    </Box>
  );
}

/**
 * 知识图谱配置项组合
 */
export function KnowledgeGraphConfigItems() {
  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
      {/* 提取知识图谱 */}
      <UseGraphragItem />
      {/* 实体类型 */}
      <EntityTypesItem />
      {/* 方法 */}
      <GraphragMethodItem />
      {/* 实体归一化 */}
      <EntityNormalizeItem />
      {/* 社区报告生成 */}
      <CommunityReportItem />
    </Box>
  );
}
