import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Form, Input, Button, message, Card, Select } from 'antd'
import { ArrowLeftOutlined } from '@ant-design/icons'
import {
  registerUnitOrOrg,
  UnitOrOrgType,
  UnitOrOrgTypeLabel,
  type UnitOrOrgRegisterParams,
} from '../api/auth'
import { setToken } from '../utils/request'
import './CompanyRegister.css'

const { Option } = Select

const unitOrOrgTypeOptions = (
  Object.entries(UnitOrOrgTypeLabel) as [UnitOrOrgType, string][]
).map(([value, label]) => ({ value, label }))

/** 表单字段类型: 接口字段 + UI 辅助字段 */
type FormValues = UnitOrOrgRegisterParams & {
  confirmPassword?: string
}

const CompanyRegister = () => {
  const navigate = useNavigate()
  const [form] = Form.useForm<FormValues>()
  const [loading, setLoading] = useState(false)

  const onFinish = async (values: FormValues) => {
    setLoading(true)
    try {
      // 剔除 UI 辅助字段
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      const { confirmPassword, ...payload } = values

      // 调用真实注册接口
      // 后端约定: success === true 表示成功, 返回值是 data 字段内容
      // 业务失败会被拦截器统一 reject + message.error,走 catch
      const result = await registerUnitOrOrg(payload)
      console.log('[单位会员注册] 响应 data:', result)

      // 可选: 保存接口返回的 accessToken,后续会员接口会透传于请求头
      const accessToken = result?.accessToken || result?.token
      if (accessToken) {
        setToken(accessToken)
      }

      message.success('注册成功,请登录!')

      // 注册成功后跳转到单位会员登录页,由用户主动登录
      setTimeout(() => {
        navigate('/company-login')
      }, 500)
    } catch (error) {
      // 请求拦截器已统一 message.error
      console.error('[单位会员注册] 失败:', error)
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="register-page">
      <div className="register-header">
        <Button
          type="text"
          icon={<ArrowLeftOutlined />}
          onClick={() => navigate(-1)}
          className="back-btn"
        />
        <h1 className="register-title">单位会员注册</h1>
      </div>

      <div className="register-form-container">
        <Form
          form={form}
          layout="vertical"
          onFinish={onFinish}
          requiredMark
          size="large"
        >
          {/* 基本信息 */}
          <Card title="基本信息" className="form-card" bordered={false}>
            <Form.Item
              label="联系人姓名"
              name="name"
              rules={[{ required: true, message: '请输入联系人姓名' }]}
            >
              <Input placeholder="请输入联系人姓名" maxLength={20} />
            </Form.Item>

            <Form.Item
              label="联系人手机号"
              name="phone"
              rules={[
                { required: true, message: '请输入手机号' },
                { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' },
              ]}
            >
              <Input placeholder="请输入联系人手机号" maxLength={11} />
            </Form.Item>

            <Form.Item
              label="单位/组织类型"
              name="unitOrOrgType"
              rules={[{ required: true, message: '请选择单位/组织类型' }]}
            >
              <Select placeholder="请选择单位/组织类型">
                {unitOrOrgTypeOptions.map((opt) => (
                  <Option key={opt.value} value={opt.value}>
                    {opt.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              label="单位地址"
              name="address"
              rules={[
                { required: true, message: '请输入单位地址' },
                { max: 200, message: '单位地址最长 200 个字符' },
              ]}
            >
              <Input placeholder="请输入单位地址" maxLength={200} />
            </Form.Item>

            <Form.Item
              label="邮编"
              name="zipCode"
              rules={[{ pattern: /^\d{6}$/, message: '请输入正确的 6 位邮编' }]}
            >
              <Input placeholder="请输入邮编" maxLength={6} />
            </Form.Item>
          </Card>

          {/* 法人代表信息 */}
          <Card title="法人代表信息" className="form-card" bordered={false}>
            <Form.Item
              label="法人代表姓名"
              name="legalPersonName"
              rules={[{ required: true, message: '请输入法人代表姓名' }]}
            >
              <Input placeholder="请输入法人代表姓名" maxLength={20} />
            </Form.Item>

            <Form.Item
              label="法人代表手机"
              name="legalPersonPhone"
              rules={[
                { required: true, message: '请输入法人代表手机号' },
                { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' },
              ]}
            >
              <Input placeholder="请输入法人代表手机号" maxLength={11} />
            </Form.Item>

            <Form.Item
              label="法人代表邮箱"
              name="legalPersonEmail"
              rules={[
                { required: true, message: '请输入法人代表邮箱' },
                { type: 'email', message: '请输入正确的邮箱地址' },
                { max: 50, message: '邮箱最长 50 个字符' },
              ]}
            >
              <Input placeholder="请输入法人代表邮箱" maxLength={50} />
            </Form.Item>
          </Card>

          {/* 推荐人信息 */}
          <Card title="推荐人信息" className="form-card" bordered={false}>
            <Form.Item label="推荐人姓名" name="referrerName">
              <Input placeholder="请输入推荐人姓名" maxLength={20} />
            </Form.Item>

            <Form.Item
              label="推荐人手机"
              name="referrerPhone"
              rules={[{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }]}
            >
              <Input placeholder="请输入推荐人手机号" maxLength={11} />
            </Form.Item>

            <Form.Item
              label="推荐人邮箱"
              name="referrerEmail"
              rules={[
                { type: 'email', message: '请输入正确的邮箱地址' },
                { max: 50, message: '邮箱最长 50 个字符' },
              ]}
            >
              <Input placeholder="请输入推荐人邮箱" maxLength={50} />
            </Form.Item>
          </Card>

          {/* 密码设置 */}
          <Card title="设置密码" className="form-card" bordered={false}>
            <Form.Item
              label="密码"
              name="password"
              rules={[
                { required: true, message: '请输入密码' },
                { min: 6, max: 20, message: '密码长度为 6-20 位' },
                {
                  pattern: /^[A-Za-z0-9!@#$%^&*()_\-+=.,?]+$/,
                  message: '密码仅支持字母、数字及常用符号',
                },
              ]}
            >
              <Input.Password placeholder="请设置密码(6-20位)" maxLength={20} />
            </Form.Item>

            <Form.Item
              label="确认密码"
              name="confirmPassword"
              dependencies={['password']}
              rules={[
                { required: true, message: '请再次输入密码' },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('password') === value) {
                      return Promise.resolve()
                    }
                    return Promise.reject(new Error('两次输入的密码不一致'))
                  },
                }),
              ]}
            >
              <Input.Password placeholder="请再次输入密码" />
            </Form.Item>
          </Card>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              className="register-submit-btn"
              loading={loading}
              block
            >
              注册
            </Button>
          </Form.Item>
        </Form>

        <p className="login-link-text">
          已有账号?
          <span className="login-link" onClick={() => navigate('/company-login')}>
            立即登入
          </span>
        </p>
      </div>
    </div>
  )
}

export default CompanyRegister
