import {
  siteapicontrollerCreatereview,
  siteapicontrollerUpdatereview,
} from '@/servers/api/siteApi';
import { Form, Input, InputNumber, Modal, Select, message } from 'antd';
import React, { useEffect } from 'react';

const { TextArea } = Input;
const { Option } = Select;

interface ReviewFormProps {
  open: boolean;
  editing: any;
  siteId: number;
  onClose: () => void;
  onSuccess: () => void;
}

const ReviewForm: React.FC<ReviewFormProps> = ({
  open,
  editing,
  siteId,
  onClose,
  onSuccess,
}) => {
  const [form] = Form.useForm();

  // 当编辑状态改变时，重置表单数据
  useEffect(() => {
    if (editing) {
      form.setFieldsValue({
        product_id: editing.product_id,
        author: editing.author,
        email: editing.email,
        content: editing.content,
        rating: editing.rating,
        status: editing.status,
      });
    } else {
      form.resetFields();
    }
  }, [editing, form]);

  // 处理表单提交
  const handleSubmit = async (values: any) => {
    try {
      let response;

      if (editing) {
        // 更新评论
        response = await siteapicontrollerUpdatereview(
          {
            siteId,
            id: editing.id,
          },
          {
            review: values.content,
            rating: values.rating,
            status: values.status,
          },
        );
      } else {
        // 创建新评论
        response = await siteapicontrollerCreatereview(
          {
            siteId,
          },
          {
            product_id: values.product_id,
            review: values.content,
            rating: values.rating,
            author: values.author,
            author_email: values.email,
          },
        );
      }

      if (response.success) {
        message.success(editing ? '更新成功' : '创建成功');
        onSuccess();
        onClose();
        form.resetFields();
      } else {
        message.error(response.message || '操作失败');
      }
    } catch (error) {
      console.error('提交评论表单失败:', error);
      message.error('提交失败，请重试');
    }
  };

  return (
    <Modal
      title={editing ? '编辑评论' : '新建评论'}
      open={open}
      onCancel={onClose}
      onOk={() => form.submit()}
      okText="保存"
      cancelText="取消"
      width={600}
    >
      <Form
        form={form}
        layout="vertical"
        onFinish={handleSubmit}
        initialValues={{
          status: 'approved',
          rating: 5,
        }}
      >
        {!editing && (
          <>
            <Form.Item
              name="product_id"
              label="产品ID"
              rules={[{ required: true, message: '请输入产品ID' }]}
            >
              <Input placeholder="请输入产品ID" />
            </Form.Item>
            <Form.Item
              name="author"
              label="评论者"
              rules={[{ required: true, message: '请输入评论者姓名' }]}
            >
              <Input placeholder="请输入评论者姓名" />
            </Form.Item>
            <Form.Item
              name="email"
              label="邮箱"
              rules={[
                { required: true, message: '请输入邮箱' },
                { type: 'email', message: '请输入有效的邮箱地址' },
              ]}
            >
              <Input placeholder="请输入邮箱" />
            </Form.Item>
          </>
        )}

        <Form.Item
          name="content"
          label="评论内容"
          rules={[{ required: true, message: '请输入评论内容' }]}
        >
          <TextArea
            rows={4}
            placeholder="请输入评论内容"
            maxLength={1000}
            showCount
          />
        </Form.Item>

        <Form.Item
          name="rating"
          label="评分"
          rules={[{ required: true, message: '请选择评分' }]}
        >
          <InputNumber
            min={1}
            max={5}
            precision={0}
            placeholder="评分 (1-5)"
            style={{ width: '100%' }}
          />
        </Form.Item>

        <Form.Item
          name="status"
          label="状态"
          rules={[{ required: true, message: '请选择状态' }]}
        >
          <Select placeholder="请选择状态">
            <Option value="approved">已批准</Option>
            <Option value="pending">待审核</Option>
            <Option value="spam">垃圾评论</Option>
            <Option value="trash">回收站</Option>
          </Select>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default ReviewForm;
