import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useForm, FormProvider, useWatch, Form } from 'react-hook-form';
import {
  Box,
  Typography,
  Card,
  CardContent,
  Button,
  Alert,
  Divider,
  Stepper,
  Step,
  StepLabel,
  CircularProgress,
} from '@mui/material';
import {
  ArrowBack as ArrowBackIcon,
  CheckCircle as CheckCircleIcon,
  SkipNext as SkipNextIcon,
} from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { useKnowledgeOperations, useKnowledgeDetail } from '@/hooks/knowledge-hooks';
import GeneralForm from './components/GeneralForm';
import ChunkMethodForm from './components/ChunkMethodForm';
import { useSnackbar } from '@/components/Provider/SnackbarProvider';
import { DOCUMENT_PARSER_TYPES } from '@/constants/knowledge';
import logger from '@/utils/logger';

function KnowledgeBaseCreate() {
  const navigate = useNavigate();
  const { t } = useTranslation();
  const [activeStep, setActiveStep] = useState(0);
  const [createdKbId, setCreatedKbId] = useState<string | null>(null);

  const steps = [t('knowledgeConfiguration.basicInfo'), t('knowledgeConfiguration.configSettings')];

  // 使用知识库操作 hooks
  const {
    loading: isSubmitting,
    error,
    createKnowledge,
    updateKnowledgeModelConfig,
    clearError
  } = useKnowledgeOperations();

  const { showMessage } = useSnackbar();

  // 获取知识库详情的hook
  const { knowledge: knowledgeDetail, refresh: refreshKnowledgeDetail } = useKnowledgeDetail(createdKbId || '');

  // 统一表单管理
  const form = useForm<any>({
    defaultValues: {
      name: '',
      description: '',
      permission: 'me',
      avatar: undefined,
      pagerank: 0,
      parser_id: DOCUMENT_PARSER_TYPES.Naive,
      embd_id: '',
      parser_config: {
        chunk_token_num: 512,
        delimiter: '\\n',
        auto_keywords: 0,
        auto_questions: 0,
        html4excel: false,
        topn_tags: 10,
        raptor: {
          use_raptor: false,
          prompt: t('knowledge.config.raptorPromptDefault'),
          max_token: 256,
          threshold: 0.1,
          max_cluster: 64,
          random_seed: 0,
        },
        graphrag: {
          use_graphrag: false,
          entity_types: ['organization', 'person', 'geo', 'event', 'category'],
          method: 'light',
        },
      },
    },
  });

  // 处理表单提交
  const handleSubmit = async ({ data }: { data: any }) => {
    logger.info('提交表单数据:', data);
    clearError();
    try {
      if (activeStep === 0) {
        // 第一步：创建知识库基础信息
        const basicData = {
          name: data.name,
          description: data.description,
          permission: data.permission,
          avatar: data.avatar,
          pagerank: data.pagerank,
          embd_id: data.embd_id,
        };

        const result = await createKnowledge(basicData);
        setCreatedKbId(result.kb_id);
        
        // 获取创建后的知识库详情，确保获取到正确的名称
        setTimeout(async () => {
          await refreshKnowledgeDetail();
        }, 500);
        
        setActiveStep(1);
        showMessage.success(t('knowledgeConfiguration.createSuccess'));
      } else {
        // 第二步：配置知识库解析设置
        if (!createdKbId) return;

        // 使用知识库详情中的正确名称，如果没有则使用表单中的名称
        const correctName = knowledgeDetail?.name || data.name;

        const configData = {
          kb_id: createdKbId,
          name: correctName, // 使用正确的名称
          description: data.description,
          permission: data.permission,
          avatar: data.avatar,
          parser_id: data.parser_id,
          pagerank: data.pagerank,
          embd_id: data.embd_id,
          parser_config: data.parser_config,
        };

        await updateKnowledgeModelConfig(configData);
        showMessage.success(t('knowledgeConfiguration.configComplete'));
        navigate('/knowledge');
      }
    } catch (err) {
      console.error('操作失败:', err);
      showMessage.error(activeStep === 0 ? t('knowledgeConfiguration.createFailed') : t('knowledgeConfiguration.configFailed'));
    }
  };

  // 跳过配置，直接完成创建
  const handleSkipConfig = async () => {
    try {
      showMessage.success(t('knowledgeConfiguration.skipConfigSuccess'));
      navigate('/knowledge');
    } catch (err) {
      console.error('跳过配置失败:', err);
      showMessage.error(t('common.operationFailed'));
    }
  };

  return (
    <Box sx={{ p: 3 }}>
      {/* 页面头部 */}
      <Box sx={{ display: 'flex', alignItems: 'center', mb: 3 }}>
        <Button
          startIcon={<ArrowBackIcon />}
          onClick={() => navigate('/knowledge')}
          sx={{ mr: 2 }}
        >
          {t('common.back')}
        </Button>
        <Typography variant="h4" component="h1">
          {t('knowledgeList.createKnowledgeBase')}
        </Typography>
      </Box>

      {/* 步骤指示器 */}
      <Card sx={{ mb: 3 }}>
        <CardContent>
          <Stepper activeStep={activeStep} alternativeLabel>
            {steps.map((label) => (
              <Step key={label}>
                <StepLabel>{label}</StepLabel>
              </Step>
            ))}
          </Stepper>
        </CardContent>
      </Card>

      {/* 错误提示 */}
      {error && (
        <Alert severity="error" sx={{ mb: 3 }}>
          {error}
        </Alert>
      )}

      {/* 表单内容 */}
      <FormProvider {...form}>
        <Form onSubmit={handleSubmit}>
          <Card>
            <CardContent>
              {activeStep === 0 ? (
                <GeneralForm form={form} />
              ) : (
                <Box>
                  <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
                    <CheckCircleIcon color="success" sx={{ mr: 1 }} />
                    <Typography variant="h6">
                      {t('knowledgeConfiguration.createSuccessConfig')}
                    </Typography>
                  </Box>
                  <Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
                    {t('knowledgeConfiguration.configLaterTip')}
                  </Typography>
                  <Divider sx={{ mb: 3 }} />
                  <ChunkMethodForm form={form} />
                </Box>
              )}

              <Divider sx={{ my: 3 }} />

              {/* 操作按钮 */}
               <Box sx={{ display: 'flex', justifyContent: 'flex-end' }}>
                 <Box sx={{ display: 'flex', gap: 2 }}>
                   {activeStep === 0 && (
                     <Button
                       variant="outlined"
                       onClick={() => navigate('/knowledge')}
                     >
                       {t('common.cancel')}
                     </Button>
                   )}
                   
                   {/* 第二步显示跳过配置按钮 */}
                   {activeStep === 1 && (
                     <Button
                       variant="outlined"
                       onClick={handleSkipConfig}
                       disabled={isSubmitting}
                       startIcon={<SkipNextIcon />}
                     >
                       {t('knowledgeConfiguration.skipConfig')}
                     </Button>
                   )}
                   
                   <Button
                     type="submit"
                     variant="contained"
                     disabled={isSubmitting}
                     startIcon={isSubmitting ? <CircularProgress size={20} /> : null}
                   >
                     {isSubmitting 
                       ? (activeStep === 0 ? t('knowledgeConfiguration.creating') : t('knowledgeConfiguration.configuring'))
                       : (activeStep === 0 ? t('knowledgeConfiguration.createAndNext') : t('knowledgeConfiguration.completeCreate'))
                     }
                   </Button>
                 </Box>
               </Box>
            </CardContent>
          </Card>
        </Form>
      </FormProvider>
    </Box>
  );
}

export default KnowledgeBaseCreate;
