import React, { useState } from 'react';
import { PageHeader, Form, Input, Card, Button, message, Spin } from 'antd';
import { fetchSpellCheck } from '@/api/spellcheck';

const { TextArea } = Input;

interface SpellCheckState {
  originalText: string;
  correctedText: string;
  loading: boolean;
  error: string | null;
}

const SpellCheckPage: React.FC = () => {
  const [form] = Form.useForm();
  const [state, setState] = useState<SpellCheckState>({
    originalText: '',
    correctedText: '',
    loading: false,
    error: null
  });

  /**
   * 处理错别字检测与修正
   */
  const handleGenerate = async () => {
    try {
      // 验证输入内容
      const values = await form.validateFields();
      const userInput = values.user_input?.trim();

      if (!userInput) {
        message.error('请输入需要检测的文本内容');
        return;
      }

      // 设置加载状态
      setState(prev => ({
        ...prev,
        originalText: userInput,
        correctedText: '',
        loading: true,
        error: null
      }));

      // 调用API获取修正结果
      const correctedResult = await fetchSpellCheck({ user_input: userInput });

      setState(prev => ({
        ...prev,
        correctedText: correctedResult,
        loading: false
      }));

      message.success('错别字检测完成');
    } catch (error) {
      console.error('错别字检测失败:', error);
      setState(prev => ({
        ...prev,
        loading: false,
        error: error instanceof Error ? error.message : '检测失败，请重试'
      }));
      message.error('检测失败，请重试');
    }
  };

  /**
   * 重置表单
   */
  const handleReset = () => {
    form.resetFields();
    setState({
      originalText: '',
      correctedText: '',
      loading: false,
      error: null
    });
  };

  return (
    <div className="flex flex-col items-center min-h-screen bg-white py-8 px-4">
      <div className="w-full max-w-4xl space-y-6">
        {/* 页面标题区 */}
        <PageHeader
          title="错别字检测与修正"
          className="!px-0 text-center"
          style={{
            fontSize: '24px',
            fontWeight: 'bold',
            color: '#1890ff'
          }}
        />

        {/* 参数输入区 */}
        <Card className="shadow-sm">
          <Form
            form={form}
            layout="vertical"
            className="space-y-4"
          >
            <Form.Item
              name="user_input"
              label={
                <span className="text-base font-medium text-gray-700">
                  待检测文本
                </span>
              }
              rules={[
                { required: true, message: '请输入需要检测的文本内容' },
                { min: 1, message: '文本内容不能为空' }
              ]}
            >
              <TextArea
                placeholder="请输入需要检测错别字的文本内容..."
                rows={6}
                className="text-base"
                disabled={state.loading}
              />
            </Form.Item>
          </Form>
        </Card>

        {/* 操作按钮区 */}
        <div className="flex justify-center space-x-4">
          <Button
            type="primary"
            size="large"
            onClick={handleGenerate}
            loading={state.loading}
            disabled={state.loading}
            className="px-8"
          >
            {state.loading ? '检测中...' : '检测错别字'}
          </Button>
          <Button
            size="large"
            onClick={handleReset}
            disabled={state.loading}
            className="px-8"
          >
            重置
          </Button>
        </div>

        {/* 内容展示区 */}
        {(state.correctedText || state.loading || state.error) && (
          <Card
            title={
              <span className="text-base font-medium text-gray-700">
                检测结果
              </span>
            }
            className="shadow-sm min-h-[200px] max-h-[60vh] overflow-y-auto"
          >
            {state.loading ? (
              <div className="flex justify-center items-center py-12">
                <Spin size="large" tip="正在检测错别字，请稍候..." />
              </div>
            ) : state.error ? (
              <div className="text-red-500 text-center py-8">
                {state.error}
              </div>
            ) : (
              <div className="space-y-4">
                {state.originalText && (
                  <div>
                    <h4 className="text-sm font-medium text-gray-600 mb-2">
                      原始文本：
                    </h4>
                    <div className="p-3 bg-gray-50 rounded border text-base leading-relaxed">
                      {state.originalText}
                    </div>
                  </div>
                )}
                {state.correctedText && (
                  <div>
                    <h4 className="text-sm font-medium text-gray-600 mb-2">
                      修正后文本：
                    </h4>
                    <div className="p-3 bg-blue-50 rounded border border-blue-200 text-base leading-relaxed">
                      {state.correctedText}
                    </div>
                  </div>
                )}
              </div>
            )}
          </Card>
        )}
      </div>
    </div>
  );
};

export default SpellCheckPage;
