import { useState } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import { Button, Form, Input, Radio, message } from 'antd'
import { ArrowLeftOutlined } from '@ant-design/icons'
import { submitInvoiceTitle } from '../api/member'
import { getUserId } from '../utils/request'
import './Invoice.css'

/** 发票类型枚举 */
export enum InvoiceType {
  /** 个人发票 */
  PERSONAL = 'PERSONAL',
  /** 单位发票 */
  UNIT = 'UNIT',
}

/** 发票表单字段 */
interface InvoiceFormValues {
  invoiceType: InvoiceType
  /** 个人抬头(invoiceType=PERSONAL) */
  personalTitle?: string
  /** 单位全称(invoiceType=UNIT) */
  unitName?: string
  /** 税号(invoiceType=UNIT) */
  taxNumber?: string
}

const Invoice = () => {
  const navigate = useNavigate()
  const location = useLocation()
  // 发票接口路径参数 {memberId} 实际使用 userId 填充
  // 优先读取路由透传,其次读取 localStorage 兑底
  const stateData = (location.state || {}) as { userId?: string }
  const userId = stateData.userId || getUserId()

  const [form] = Form.useForm<InvoiceFormValues>()
  const [submitting, setSubmitting] = useState(false)
  const [invoiceType, setInvoiceType] = useState<InvoiceType>(
    InvoiceType.PERSONAL
  )

  /** 切换发票类型, 清空已不再需要的字段 */
  const handleTypeChange = (value: InvoiceType) => {
    setInvoiceType(value)
    if (value === InvoiceType.PERSONAL) {
      form.setFieldsValue({ unitName: undefined, taxNumber: undefined })
    } else if (value === InvoiceType.UNIT) {
      form.setFieldsValue({ personalTitle: undefined })
    }
  }

  const handleSubmit = async (values: InvoiceFormValues) => {
    if (!userId) {
      message.error('未获取到用户信息,请重新登录后重试')
      return
    }

    // 根据发票类型组装接口请求体
    // - 个人发票: invoiceTitle = personalTitle, invoiceTaxNo 不传
    // - 单位发票: invoiceTitle = unitName, invoiceTaxNo = taxNumber
    const payload =
      values.invoiceType === InvoiceType.PERSONAL
        ? { invoiceTitle: values.personalTitle }
        : {
            invoiceTitle: values.unitName,
            invoiceTaxNo: values.taxNumber,
          }

    setSubmitting(true)
    try {
      const ok = await submitInvoiceTitle(userId, payload)
      console.log('[Invoice submit]', { userId, payload, ok })
      // 后端约定: data 字段为 boolean,true 表示提交成功
      if (ok === false) {
        message.error('提交失败,请稍后重试')
        return
      }
      message.success('发票信息提交成功!')
      setTimeout(() => navigate(-1), 600)
    } catch (e) {
      // 请求拦截器已统一 message.error,这里不重复提示
      console.error('[Invoice submit error]', e)
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <div className="invoice-page">
      <div className="invoice-header">
        <Button
          type="text"
          icon={<ArrowLeftOutlined />}
          onClick={() => navigate(-1)}
          className="back-btn"
        />
        <h1 className="invoice-title">填写发票信息</h1>
        <span className="header-spacer" />
      </div>

      <div className="invoice-container">
        <Form<InvoiceFormValues>
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          initialValues={{ invoiceType: InvoiceType.PERSONAL }}
          className="invoice-form"
        >
          <Form.Item
            label="发票类型"
            name="invoiceType"
            rules={[{ required: true, message: '请选择发票类型' }]}
          >
            <Radio.Group
              onChange={(e) => handleTypeChange(e.target.value)}
              className="invoice-type-group"
            >
              <Radio.Button value={InvoiceType.PERSONAL}>个人发票</Radio.Button>
              <Radio.Button value={InvoiceType.UNIT}>单位发票</Radio.Button>
            </Radio.Group>
          </Form.Item>

          {/* 个人发票: 个人抬头 */}
          {invoiceType === InvoiceType.PERSONAL && (
            <Form.Item
              label="个人抬头"
              name="personalTitle"
              rules={[
                { required: true, message: '请输入个人抬头' },
                { max: 50, message: '最多 50 个字符' },
              ]}
            >
              <Input placeholder="请输入个人抬头(如本人姓名)" allowClear />
            </Form.Item>
          )}

          {/* 单位发票: 单位全称 + 税号 */}
          {invoiceType === InvoiceType.UNIT && (
            <>
              <Form.Item
                label="单位全称"
                name="unitName"
                rules={[
                  { required: true, message: '请输入单位全称' },
                  { max: 100, message: '最多 100 个字符' },
                ]}
              >
                <Input placeholder="请输入单位全称(发票抬头)" allowClear />
              </Form.Item>
              <Form.Item
                label="税号"
                name="taxNumber"
                rules={[
                  { required: true, message: '请输入纳税人识别号' },
                  {
                    pattern: /^[A-Z0-9]{15,20}$/,
                    message: '税号为 15-20 位数字或大写字母',
                  },
                ]}
                normalize={(v: string) => (v ? v.toUpperCase() : v)}
              >
                <Input
                  placeholder="请输入纳税人识别号(15-20 位)"
                  maxLength={20}
                  allowClear
                />
              </Form.Item>
            </>
          )}

          <Form.Item className="submit-item">
            <Button
              type="primary"
              htmlType="submit"
              block
              size="large"
              loading={submitting}
              className="submit-btn"
            >
              提交
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

export default Invoice
