import { useMemo } from 'react';
import { Button, Form, Input, Modal, Select } from 'antd';
import type { FormInstance } from 'antd';
import dayjs from 'dayjs';
import type { PointsMallProduct } from '../../../api';
import type { ExchangeFormValues } from '../types';

export default function ExchangeModal(props: {
  open: boolean;
  product: PointsMallProduct | null;
  quantity?: number;
  expiresAt?: string | null;
  loading: boolean;
  form: FormInstance<ExchangeFormValues>;
  onSubmit: () => void;
  onCancel: () => void;
}) {
  const { open, product, quantity, expiresAt, loading, form, onSubmit, onCancel } = props;
  const qty = Math.max(1, Number(quantity || 1));
  const totalPoints = product ? product.pointsPrice * qty : 0;
  const expiresText = expiresAt ? dayjs(expiresAt).format('YYYY-MM-DD HH:mm:ss') : null;
  const province = Form.useWatch('province', form);
  const city = Form.useWatch('city', form);

  const region = useMemo(() => {
    return {
      provinces: [
        {
          name: '北京市',
          cities: [
            {
              name: '北京市',
              districts: ['东城区', '西城区', '朝阳区', '海淀区', '丰台区', '石景山区', '通州区', '昌平区', '大兴区', '顺义区']
            }
          ]
        },
        {
          name: '上海市',
          cities: [
            {
              name: '上海市',
              districts: ['黄浦区', '徐汇区', '长宁区', '静安区', '普陀区', '虹口区', '杨浦区', '浦东新区', '闵行区', '宝山区']
            }
          ]
        },
        {
          name: '广东省',
          cities: [
            { name: '广州市', districts: ['越秀区', '天河区', '海珠区', '白云区', '番禺区'] },
            { name: '深圳市', districts: ['福田区', '南山区', '罗湖区', '宝安区', '龙岗区'] }
          ]
        },
        { name: '浙江省', cities: [{ name: '杭州市', districts: ['上城区', '拱墅区', '西湖区', '滨江区', '萧山区', '余杭区'] }] },
        { name: '江苏省', cities: [{ name: '南京市', districts: ['玄武区', '秦淮区', '建邺区', '鼓楼区', '雨花台区', '江宁区'] }] }
      ]
    };
  }, []);

  const cityOptions = useMemo(() => {
    const p = region.provinces.find((x) => x.name === province);
    return (p?.cities || []).map((c) => ({ value: c.name, label: c.name }));
  }, [province, region.provinces]);

  const districtOptions = useMemo(() => {
    const p = region.provinces.find((x) => x.name === province);
    const c = p?.cities.find((x) => x.name === city);
    return (c?.districts || []).map((d) => ({ value: d, label: d }));
  }, [province, city, region.provinces]);

  return (
    <Modal title="兑换商品" open={open} onCancel={onCancel} footer={null} width={500} className="points-exchange-modal" destroyOnClose>
      {product && (
        <>
          <div className="points-exchange-modal-header">
            <div className="points-mall-exchange-modal-title">{product.name}</div>
            <div className="points-mall-exchange-modal-points">
              {totalPoints.toLocaleString()} 积分{qty > 1 ? `（${qty} 件）` : ''}
            </div>
          </div>

          {expiresText && (
            <div className="points-exchange-expire-tip">已冻结积分并预扣库存，请在 {expiresText} 前提交收件信息，超时将自动释放。</div>
          )}

          <Form form={form} layout="vertical" className="points-exchange-form">
            <Form.Item
              name="recipientName"
              label={<span className="points-exchange-form-label">收货人姓名</span>}
              rules={[{ required: true, message: '请输入收货人姓名' }]}
              className="points-exchange-form-item"
            >
              <Input placeholder="请输入收货人姓名" className="points-exchange-form-input" />
            </Form.Item>

            <Form.Item
              name="phone"
              label={<span className="points-exchange-form-label">手机号码</span>}
              rules={[{ required: true, message: '请输入手机号码' }, { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }]}
              className="points-exchange-form-item"
            >
              <Input placeholder="请输入手机号码" className="points-exchange-form-input" />
            </Form.Item>

            <div className="points-mall-address-grid">
              <Form.Item
                name="province"
                label={<span className="points-exchange-form-label">省份</span>}
                rules={[{ required: true, message: '请选择省份' }]}
                className="points-exchange-form-item points-exchange-form-item-small"
              >
                <Select
                  placeholder="省份"
                  className="points-exchange-form-input"
                  options={region.provinces.map((p) => ({ value: p.name, label: p.name }))}
                  onChange={() => {
                    form.setFieldsValue({ city: undefined, district: undefined } as any);
                  }}
                />
              </Form.Item>

              <Form.Item
                name="city"
                label={<span className="points-exchange-form-label">城市</span>}
                rules={[{ required: true, message: '请选择城市' }]}
                className="points-exchange-form-item points-exchange-form-item-small"
              >
                <Select
                  placeholder="城市"
                  className="points-exchange-form-input"
                  options={cityOptions}
                  disabled={!province}
                  onChange={() => {
                    form.setFieldsValue({ district: undefined } as any);
                  }}
                />
              </Form.Item>

              <Form.Item
                name="district"
                label={<span className="points-exchange-form-label">区/县</span>}
                rules={[{ required: true, message: '请选择区/县' }]}
                className="points-exchange-form-item points-exchange-form-item-small"
              >
                <Select placeholder="区/县" className="points-exchange-form-input" options={districtOptions} disabled={!province || !city} />
              </Form.Item>
            </div>

            <Form.Item
              name="address"
              label={<span className="points-exchange-form-label">详细地址</span>}
              rules={[{ required: true, message: '请输入详细地址' }]}
              className="points-exchange-form-item"
            >
              <Input.TextArea placeholder="请输入详细地址（街道、门牌号等）" rows={3} className="points-exchange-form-input" />
            </Form.Item>

            <Form.Item
              name="zipCode"
              label={<span className="points-exchange-form-label">邮政编码（选填）</span>}
              className="points-exchange-form-item"
            >
              <Input placeholder="请输入邮政编码" className="points-exchange-form-input" />
            </Form.Item>

            <Button
              type="primary"
              className="points-exchange-submit-btn"
              onClick={onSubmit}
              loading={loading}
              disabled={loading}
            >
              确认兑换
            </Button>
          </Form>
        </>
      )}
    </Modal>
  );
}
