import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Form, Input, Select, Button, message, Card } from 'antd'
import { ArrowLeftOutlined } from '@ant-design/icons'
import {
  registerPersonal,
  GenderLabel,
  PoliticalStatusLabel,
  EducationLevelLabel,
  ProfessionalTitleLabel,
  RegionOrUnitLabel,
  PersonalMemberType,
  PersonalMemberTypeLabel,
  type PersonalRegisterParams,
} from '../api/auth'
import { setToken } from '../utils/request'
import './Register.css'

const { Option } = Select

/** 将枚举映射对象转换为下拉 options */
const enumToOptions = <T extends string>(labelMap: Record<T, string>) =>
  Object.entries(labelMap).map(([value, label]) => ({
    value: value as T,
    label: label as string,
  }))

const genderOptions = enumToOptions(GenderLabel)
const politicalStatusOptions = enumToOptions(PoliticalStatusLabel)
const educationOptions = enumToOptions(EducationLevelLabel)
const titleOptions = enumToOptions(ProfessionalTitleLabel)
const regionOptions = enumToOptions(RegionOrUnitLabel)
const memberTypeOptions = enumToOptions(PersonalMemberTypeLabel)

// 地区(地区中医药学/协会会长、秘书长场景使用,金华市内区县)
const cityOptions = [
  '婺城区', '金东区', '开发区', '义乌市', '兰溪市', '东阳市',
  '永康市', '浦江县', '武义县', '磐安县',
]

/** 表单字段类型: 包含 PersonalRegisterParams + UI 辅助字段 */
type FormValues = PersonalRegisterParams & {
  confirmPassword?: string
  cityAssociation?: string
}

const PersonalRegister = () => {
  const navigate = useNavigate()
  const [form] = Form.useForm<FormValues>()
  const [memberType, setMemberType] = useState<PersonalMemberType | undefined>(
    PersonalMemberType.SPECIAL_COMMITTEE_MEMBER,
  )
  const [loading, setLoading] = useState(false)

  const onFinish = async (values: FormValues) => {
    setLoading(true)
    try {
      // 提取接口需要的字段(去掉 confirmPassword 和 UI 辅助字段)
      const {
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        confirmPassword,
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        cityAssociation,
        ...payload
      } = values

      // 非专科分会委员不传 specialCommitteeMemberType
      if (
        payload.memberType !== PersonalMemberType.SPECIAL_COMMITTEE_MEMBER
      ) {
        delete payload.specialCommitteeMemberType
      }

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

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

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

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

  const handleMemberTypeChange = (value: PersonalMemberType) => {
    setMemberType(value)
    if (value !== PersonalMemberType.SPECIAL_COMMITTEE_MEMBER) {
      form.setFieldValue('specialCommitteeMemberType', undefined)
    }
    if (value !== PersonalMemberType.REGIONAL_ASSOCIATION_LEADER) {
      form.setFieldValue('cityAssociation', undefined)
    }
  }

  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="gender"
              rules={[{ required: true, message: '请选择性别' }]}
            >
              <Select placeholder="请选择性别">
                {genderOptions.map((opt) => (
                  <Option key={opt.value} value={opt.value}>
                    {opt.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              label="身份证"
              name="identityCard"
              rules={[
                { required: true, message: '请输入身份证号' },
                {
                  pattern:
                    /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/,
                  message: '请输入正确的 18 位身份证号',
                },
              ]}
            >
              <Input placeholder="请输入身份证号" maxLength={18} />
            </Form.Item>

            <Form.Item
              label="政治面貌"
              name="politicalStatus"
              rules={[{ required: true, message: '请选择政治面貌' }]}
            >
              <Select placeholder="请选择政治面貌" showSearch optionFilterProp="children">
                {politicalStatusOptions.map((opt) => (
                  <Option key={opt.value} value={opt.value}>
                    {opt.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              label="学历"
              name="educationLevel"
              rules={[{ required: true, message: '请选择学历' }]}
            >
              <Select placeholder="请选择学历">
                {educationOptions.map((opt) => (
                  <Option key={opt.value} value={opt.value}>
                    {opt.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              label="职称"
              name="title"
            >
              <Select
                placeholder="请选择职称"
                showSearch
                optionFilterProp="children"
                allowClear
              >
                {titleOptions.map((opt) => (
                  <Option key={opt.value} value={opt.value}>
                    {opt.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              label="职务"
              name="position"
              rules={[{ max: 50, message: '职务最长 50 个字符' }]}
            >
              <Input placeholder="请输入职务" maxLength={50} />
            </Form.Item>

            <Form.Item
              label="所属地区/单位"
              name="regionOrUnit"
              rules={[{ required: true, message: '请选择所属地区/单位' }]}
            >
              <Select placeholder="请选择所属地区/单位" showSearch optionFilterProp="children">
                {regionOptions.map((opt) => (
                  <Option key={opt.value} value={opt.value}>
                    {opt.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>

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

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

            <Form.Item
              label="邮箱"
              name="email"
              rules={[
                { required: true, message: '请输入邮箱' },
                { type: 'email', message: '请输入正确的邮箱地址' },
                { max: 50, message: '邮箱最长 50 个字符' },
              ]}
            >
              <Input placeholder="请输入邮箱" maxLength={50} />
            </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="memberType"
              rules={[{ required: true, message: '请选择会员类型' }]}
            >
              <Select
                placeholder="请选择会员类型"
                onChange={handleMemberTypeChange}
              >
                {memberTypeOptions.map((opt) => (
                  <Option key={opt.value} value={opt.value}>
                    {opt.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>

            {/* 专科分会委员 - 条件显示(对接 specialCommitteeMemberType) */}
            {memberType === PersonalMemberType.SPECIAL_COMMITTEE_MEMBER && (
              <Form.Item
                label="专科分会"
                name="specialCommitteeMemberType"
                rules={[{ required: true, message: '请选择或输入专科分会' }]}
              >
                <Select
                  placeholder="请选择或搜索专科分会"
                  showSearch
                  optionFilterProp="children"
                >
                  <Option value="内科分会">内科分会</Option>
                  <Option value="外科分会">外科分会</Option>
                  <Option value="针灸分会">针灸分会</Option>
                  <Option value="推拿分会">推拿分会</Option>
                </Select>
              </Form.Item>
            )}

            {/* 地区中医药学(协)会会长、秘书长 - 条件显示 */}
            {memberType === PersonalMemberType.REGIONAL_ASSOCIATION_LEADER && (
              <Form.Item
                label="地区中医药学(协)会"
                name="cityAssociation"
                rules={[{ required: true, message: '请选择地区' }]}
              >
                <Select placeholder="请选择地区">
                  {cityOptions.map((option) => (
                    <Option key={option} value={option}>
                      {option}
                    </Option>
                  ))}
                </Select>
              </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('/personal-login')}>
            立即登入
          </span>
        </p>
      </div>
    </div>
  )
}

export default PersonalRegister
