import React, { useEffect, useState } from 'react';
import { Form, Input, InputNumber, Select, DatePicker, Button, Card, message, Spin } from 'antd';
import { useNavigate, useParams } from 'react-router-dom';
import { ArrowLeftOutlined } from '@ant-design/icons';
import { createCoupon, updateCoupon, getCouponDetail } from '@/api/coupon';
import dayjs from 'dayjs';

const { RangePicker } = DatePicker;
const { Option } = Select;

const CouponForm: React.FC = () => {
  const navigate = useNavigate();
  const { id } = useParams<{ id: string }>();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [couponType, setCouponType] = useState<string>('fixed');

  const isEdit = !!id;

  useEffect(() => {
    if (isEdit) {
      fetchDetail();
    }
  }, [id]);

  const fetchDetail = async () => {
    setLoading(true);
    try {
      const res: any = await getCouponDetail(Number(id));
      const coupon = res.data;
      form.setFieldsValue({
        name: coupon.name,
        type: coupon.type,
        value: coupon.value,
        minAmount: coupon.minAmount,
        totalCount: coupon.totalCount,
        dateRange: [dayjs(coupon.startDate), dayjs(coupon.endDate)],
        scope: coupon.scope,
        scopeId: coupon.scopeId,
      });
      setCouponType(coupon.type);
    } catch (error) {
      message.error('加载失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (values: any) => {
    setSubmitting(true);
    try {
      const data = {
        name: values.name,
        type: values.type,
        value: values.value,
        minAmount: values.minAmount,
        totalCount: values.totalCount,
        startDate: values.dateRange[0].format('YYYY-MM-DD'),
        endDate: values.dateRange[1].format('YYYY-MM-DD'),
        scope: values.scope,
        scopeId: values.scopeId || undefined,
      };

      if (isEdit) {
        await updateCoupon(Number(id), { totalCount: data.totalCount });
        message.success('更新成功');
      } else {
        await createCoupon(data);
        message.success('创建成功');
      }
      navigate('/coupons');
    } catch (error: any) {
      message.error(error.message || '操作失败');
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '100px 0' }}>
        <Spin size="large" />
      </div>
    );
  }

  return (
    <div>
      <Button
        icon={<ArrowLeftOutlined />}
        onClick={() => navigate('/coupons')}
        style={{ marginBottom: 16 }}
      >
        返回
      </Button>

      <Card title={isEdit ? '编辑优惠券' : '创建优惠券'}>
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          initialValues={{
            type: 'fixed',
            minAmount: 0,
            totalCount: 100,
            scope: 'platform',
          }}
        >
          <Form.Item
            label="优惠券名称"
            name="name"
            rules={[{ required: true, message: '请输入优惠券名称' }]}
          >
            <Input placeholder="例如：新人专享券" maxLength={100} disabled={isEdit} />
          </Form.Item>

          <Form.Item
            label="优惠券类型"
            name="type"
            rules={[{ required: true, message: '请选择优惠券类型' }]}
          >
            <Select
              onChange={(value) => setCouponType(value)}
              disabled={isEdit}
            >
              <Option value="fixed">满减券</Option>
              <Option value="percent">折扣券</Option>
            </Select>
          </Form.Item>

          <Form.Item
            label={couponType === 'fixed' ? '优惠金额（元）' : '折扣比例（%）'}
            name="value"
            rules={[
              { required: true, message: '请输入优惠值' },
              {
                validator: (_, value) => {
                  if (couponType === 'percent' && (value < 1 || value > 99)) {
                    return Promise.reject('折扣比例必须在1-99之间');
                  }
                  return Promise.resolve();
                },
              },
            ]}
          >
            <InputNumber
              min={couponType === 'fixed' ? 0.01 : 1}
              max={couponType === 'fixed' ? 99999 : 99}
              precision={2}
              style={{ width: '100%' }}
              placeholder={couponType === 'fixed' ? '例如：10' : '例如：85（表示8.5折）'}
              disabled={isEdit}
            />
          </Form.Item>

          <Form.Item
            label="最低使用金额（元）"
            name="minAmount"
            rules={[{ required: true, message: '请输入最低使用金额' }]}
          >
            <InputNumber
              min={0}
              precision={2}
              style={{ width: '100%' }}
              placeholder="0表示无门槛"
              disabled={isEdit}
            />
          </Form.Item>

          <Form.Item
            label="发放总量"
            name="totalCount"
            rules={[{ required: true, message: '请输入发放总量' }]}
          >
            <InputNumber
              min={1}
              style={{ width: '100%' }}
              placeholder="例如：100"
            />
          </Form.Item>

          <Form.Item
            label="有效期"
            name="dateRange"
            rules={[{ required: true, message: '请选择有效期' }]}
          >
            <RangePicker style={{ width: '100%' }} disabled={isEdit} />
          </Form.Item>

          <Form.Item
            label="适用范围"
            name="scope"
            rules={[{ required: true, message: '请选择适用范围' }]}
          >
            <Select disabled={isEdit}>
              <Option value="platform">平台通用</Option>
              <Option value="merchant">指定商家</Option>
              <Option value="room">指定房源</Option>
            </Select>
          </Form.Item>

          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) =>
              prevValues.scope !== currentValues.scope
            }
          >
            {({ getFieldValue }) =>
              getFieldValue('scope') !== 'platform' ? (
                <Form.Item
                  label={getFieldValue('scope') === 'merchant' ? '商家ID' : '房源ID'}
                  name="scopeId"
                  rules={[{ required: true, message: '请输入ID' }]}
                >
                  <InputNumber
                    min={1}
                    style={{ width: '100%' }}
                    placeholder="请输入ID"
                    disabled={isEdit}
                  />
                </Form.Item>
              ) : null
            }
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" loading={submitting}>
              {isEdit ? '保存' : '创建'}
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={() => navigate('/coupons')}>
              取消
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default CouponForm;
