import React, { useState, useEffect } from 'react';
import { Form, Input, Switch, Tabs, message, Button, Select } from 'antd';
import WangEditor from '@/components/WangEidtor/WangEidtor';
import { TopStatus, EnglishSetting, categoryOptions } from '@/dicts/helpManageDict';
import { addHelp, updateHelp, getHelpDetail } from '@/servers/api/help';

const { TabPane } = Tabs;
const { Option } = Select;

interface HelpManageFormProps {
  id?: string;
  isEdit: boolean;
  onSuccess: () => void;
}

const HelpManageForm: React.FC<HelpManageFormProps> = ({ id, isEdit, onSuccess }) => {
  const [form] = Form.useForm();
  const [activeTabKey, setActiveTabKey] = useState<string>('zh');
  const [loading, setLoading] = useState<boolean>(false);

  // 获取详情数据
  useEffect(() => {
    const fetchHelpDetail = async (helpId: string) => {
      setLoading(true);
      try {
        const response = await getHelpDetail(helpId);
        if (response && response.success) {
          const detail = response.data;
          form.setFieldsValue({
            isTop: detail.isTop === TopStatus.YES,
            type: detail.type,
            titleZh: detail.title,
            titleEn: detail.titleEn,
            contentZh: detail.content,
            contentEn: detail.contentEn,
            answerContentZh: detail.answerContent,
            answerContentEn: detail.answerContentNe,
          });
        } else {
          message.error(response.message || '获取详情失败');
        }
      } catch (error) {
        console.error('获取帮助详情失败:', error);
        message.error('获取详情失败');
      } finally {
        setLoading(false);
      }
    };

    if (isEdit && id) {
      fetchHelpDetail(id);
    }
  }, [isEdit, id, form]);

  // 处理Tab切换
  const handleTabChange = (key: string) => {
    setActiveTabKey(key);
  };

  // 提交表单
  const handleSubmit = async () => {
    setLoading(true);
    try {
      // 一次性验证所有表单项
      try {
        await form.validateFields();
      } catch (error: any) {
        console.log(error);
        // 如果有验证错误，自动切换到相应Tab
        if (error.errorFields && error.errorFields.length > 0) {
          // 获取第一个错误字段
          const firstError = error.errorFields[0];
          const fieldName = firstError.name[0];

          // 根据字段名判断应该切换到哪个Tab
          if (fieldName === 'titleZh' || fieldName === 'contentZh' || fieldName === 'answerContentZh') {
            setActiveTabKey('zh');
          } else if (fieldName === 'titleEn' || fieldName === 'contentEn' || fieldName === 'answerContentEn') {
            setActiveTabKey('en');
          }
        }

        throw error;
      }

      // 获取所有表单值
      const values = form.getFieldsValue();

      // 转换表单数据为API需要的格式
      const requestData = {
        title: values.titleZh,
        titleEn: values.titleEn || '',
        content: values.contentZh,
        contentEn: values.contentEn || '',
        type: values.type,
        isTop: values.isTop ? TopStatus.YES : TopStatus.NO,
        settingEn: values.titleEn && values.contentEn ? EnglishSetting.YES : EnglishSetting.NO,
        answerContent: values.answerContentZh || '',
        answerContentNe: values.answerContentEn || '',
      };

      let response;
      if (isEdit && id) {
        response = await updateHelp(id, requestData);
      } else {
        response = await addHelp(requestData);
      }

      if (response && response.success) {
        message.success(isEdit ? '更新成功' : '添加成功');
        onSuccess(); // 回调父组件
      } else {
        message.error(response.message || (isEdit ? '更新失败' : '添加失败'));
      }
    } catch (error: any) {
      console.error('表单验证或提交失败:', error);
      // 错误已在前面处理
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <Form form={form} layout="vertical" name="helpForm" preserve={false}>
        <Form.Item name="isTop" label="是否置顶" valuePropName="checked">
          <Switch />
        </Form.Item>

        <Form.Item
          name="type"
          label="问题类型"
          rules={[{ required: true, message: '请选择问题类型' }]}
        >
          <Select placeholder="请选择问题类型">
            {categoryOptions.map(option => (
              <Option key={option.value} value={option.value}>
                {option.label}
              </Option>
            ))}
          </Select>
        </Form.Item>

        <Tabs activeKey={activeTabKey} onChange={handleTabChange}>
          <TabPane tab="中文版" key="zh" forceRender={true}>
            <Form.Item
              name="titleZh"
              label="标题（中文）"
              rules={[{ required: true, message: '请输入中文标题' }]}
            >
              <Input placeholder="请输入中文标题" />
            </Form.Item>

            <Form.Item
              name="contentZh"
              label="内容（中文）"
              rules={[{ required: true, message: '请输入中文内容' }]}
            >
              <WangEditor language="zh-CN" height="250px" placeholder="请输入帮助内容..." />
            </Form.Item>

            <Form.Item
              name="answerContentZh"
              label="回答内容（中文）"
            >
              <WangEditor language="zh-CN" height="200px" placeholder="请输入回答内容..." />
            </Form.Item>
          </TabPane>
          <TabPane tab="英文版" key="en" forceRender={true}>
            <Form.Item
              name="titleEn"
              label="标题（英文）"
              rules={[{ required: true, message: 'Please enter title in English' }]}
            >
              <Input placeholder="Please enter title in English" />
            </Form.Item>

            <Form.Item
              name="contentEn"
              label="内容（英文）"
              rules={[{ required: true, message: 'Please enter content in English' }]}
            >
              <WangEditor
                language="en"
                height="250px"
                placeholder="Please enter help content..."
              />
            </Form.Item>

            <Form.Item
              name="answerContentEn"
              label="回答内容（英文）"
            >
              <WangEditor
                language="en"
                height="200px"
                placeholder="Please enter answer content..."
              />
            </Form.Item>
          </TabPane>
        </Tabs>
      </Form>
      <div style={{ textAlign: 'right', marginTop: '20px' }}>
        <Button onClick={() => onSuccess()}>取消</Button>
        <Button
          type="primary"
          loading={loading}
          onClick={handleSubmit}
          style={{ marginLeft: '8px' }}
        >
          提交
        </Button>
      </div>
    </div>
  );
};

export default HelpManageForm;
