import React, { useMemo, useState, useEffect } from 'react';
import { useFormContext, useWatch, type UseFormReturn } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import {
  Box,
  Typography,
  Button,
  Card,
  CardContent,
} from '@mui/material';
import { DocumentParserType, ParseType } from '@/constants/knowledge';
import { type IParserConfig } from '@/interfaces/database/knowledge';
import {
  NaiveConfiguration,
  QAConfiguration,
  PaperConfiguration,
  ResumeConfiguration,
  ManualConfiguration,
  TableConfiguration,
  BookConfiguration,
  LawsConfiguration,
  PresentationConfiguration,
  OneConfiguration,
  TagConfiguration,
  ConfigurationFormContainer,
  MainContainer,
} from '../configuration';
import { ChunkMethodItem } from '../configuration';
import { PipelineSelectorItem } from '../configuration/common-items';
import { RadioFormField } from '@/components/FormField';

// 配置组件映射表
const ConfigurationComponentMap = {
  [DocumentParserType.Naive]: NaiveConfiguration,
  [DocumentParserType.Qa]: QAConfiguration,
  [DocumentParserType.Resume]: ResumeConfiguration,
  [DocumentParserType.Manual]: ManualConfiguration,
  [DocumentParserType.Table]: TableConfiguration,
  [DocumentParserType.Paper]: PaperConfiguration,
  [DocumentParserType.Book]: BookConfiguration,
  [DocumentParserType.Laws]: LawsConfiguration,
  [DocumentParserType.Presentation]: PresentationConfiguration,
  [DocumentParserType.One]: OneConfiguration,
  [DocumentParserType.Tag]: TagConfiguration,
  [DocumentParserType.KnowledgeGraph]: TagConfiguration,
  [DocumentParserType.Picture]: TagConfiguration,
  [DocumentParserType.Audio]: TagConfiguration,
  [DocumentParserType.Email]: TagConfiguration,
  // [DOCUMENT_PARSER_TYPES.KnowledgeGraph]: KnowledgeGraphConfiguration,
  // [DOCUMENT_PARSER_TYPES.Picture]: PictureConfiguration,
  // [DOCUMENT_PARSER_TYPES.Audio]: AudioConfiguration,
  // [DOCUMENT_PARSER_TYPES.Email]: GraphragConfiguration,
};

// 空组件
function EmptyComponent() {
  const { t } = useTranslation();
  return (
    <Box sx={{ textAlign: 'center', py: 4 }}>
      <Typography color="text.secondary">
        {t('knowledge.selectParserMethod')}
      </Typography>
    </Box>
  );
}

export interface ConfigFormData extends IParserConfig {
  parser_id: DocumentParserType;
}

interface ChunkMethodFormProps {
  form?: UseFormReturn;
  onSubmit?: (data: any) => void;
  isSubmitting?: boolean;
  onCancel?: () => void;
  submitButtonText?: string;
  cancelButtonText?: string;
}


function ChunkMethodForm({
  form: propForm,
  onSubmit,
  isSubmitting,
  onCancel,
  submitButtonText,
  cancelButtonText,
}: ChunkMethodFormProps = {}) {
  const { t } = useTranslation();
  // 优先使用props传递的form，否则使用FormProvider的context
  let contextForm;
  try {
    contextForm = useFormContext();
  } catch (error) {
    contextForm = null;
  }

  const form = propForm || contextForm;

  if (!form) {
    console.error('ChunkMethodForm: No form context found. Component must be used within a FormProvider or receive a form prop.');
    return (
      <Box sx={{ p: 2, textAlign: 'center' }}>
        <Typography color="error">
          {t('form.formConfigError')}
        </Typography>
      </Box>
    );
  }

  const { control } = form;

  // 监听parser_id变化
  const parser_id = useWatch({
    control,
    name: 'parser_id',
  });

  // 监听 pipeline_id，自动决定构建模式
  const pipeline_id = useWatch({
    control,
    name: 'pipeline_id',
  });
  const [parseType, setParseType] = useState<ParseType>(pipeline_id ? ParseType.Pipeline : ParseType.BuildIn);
  
  useEffect(() => {
    setParseType(pipeline_id ? ParseType.Pipeline : ParseType.BuildIn);
  }, [pipeline_id]);

  // 根据parser_id动态选择配置组件
  const ConfigurationComponent = useMemo(() => {
    const parser = parser_id as DocumentParserType;
    const component = ConfigurationComponentMap[parser] || EmptyComponent;
    return component || EmptyComponent;
  }, [parser_id]);

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
      {/* 构建模式选择与联动 */}
      <Card sx={{ px: 3, marginX: 3 }}>
        <CardContent>
        <RadioFormField
          name="parseType"
          label={t('knowledgeConfiguration.parseType')}
          defaultValue={parseType}
          options={[
            { value: ParseType.BuildIn, label: 'Built-in' },
            { value: ParseType.Pipeline, label: 'Pipeline' },
          ]}
          onChangeValue={(v) => setParseType(v as ParseType)}
        />

        {/* 基于模式：内置显示切片方法，Pipeline 显示选择器 */}
        {parseType === ParseType.BuildIn ? (
          <ChunkMethodItem />
        ) : (
          <PipelineSelectorItem />
        )}
        </CardContent>
      </Card>

      {/* 动态配置内容：始终渲染，内部按 parseType 控制基础配置显示 */}
      <ConfigurationComponent parseType={parseType} />

      {/* 表单操作按钮 - 仅在有onSubmit回调时显示 */}
      {onSubmit && (
        <Box sx={{ mt: 4, display: 'flex', justifyContent: 'flex-end', gap: 2 }}>
          {onCancel && (
            <Button
              variant="outlined"
              onClick={onCancel}
              disabled={isSubmitting}
            >
              {cancelButtonText || t('common.cancel')}
            </Button>
          )}
          <Button
            variant="contained"
            onClick={form ? form.handleSubmit(onSubmit) : undefined}
            disabled={isSubmitting || !form}
          >
            {isSubmitting ? t('common.submitting') : (submitButtonText || t('common.save'))}
          </Button>
        </Box>
      )}
    </Box>
  );
}

export default ChunkMethodForm;
