import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Form, Input, Button, message, Card } from 'antd'
import { ArrowLeftOutlined, UserOutlined, LockOutlined } from '@ant-design/icons'
import { loginPersonal } from '../api/auth'
import { setToken, setUserId, setMemberNo } from '../utils/request'
import './Login.css'

const PersonalLogin = () => {
  const navigate = useNavigate()
  const [loading, setLoading] = useState(false)

  const onFinish = async (values: { phone: string; password: string }) => {
    setLoading(true)
    try {
      // 调用真实登录接口 (yapi mock)
      const result = await loginPersonal({
        phone: values.phone,
        password: values.password,
      })
      console.log('[个人会员登录] 响应:', result)

      // 保存后端返回的 accessToken (后续会员接口 Authorization 头都使用此 token)
      const accessToken = result?.accessToken || result?.token
      if (accessToken) {
        setToken(accessToken)
      }

      // 保存后端返回的 userId (会员权益页面需要展示)
      const userId = (result?.userId as string) || ''
      if (userId) {
        setUserId(userId)
      }

      // 保存后端返回的 memberNo (会员编号,发票接口路径参数也使用)
      const memberNo = (result?.memberNo as string) || ''
      if (memberNo) {
        setMemberNo(memberNo)
      }

      // 根据后端返回的 isVip 判断会员状态
      // - isVip = true: 已充值会员 -> 会员权益页(/member-valid)
      // - isVip = false/未返回: 未充值 -> 支付页(/payment)
      const isVip = result?.isVip === true
      const memberInfo = {
        userId,
        memberNo,
        memberId: (result?.memberId as string) || '',
        memberType: '个人会员',
        amount: 150.0,
        validPeriod: '5年',
        registerTime: (result?.registerTime as string) || '',
        expireTime: (result?.expireTime as string) || '',
        invoiceTitle: (result?.invoiceTitle as string) || '',
        invoiceTaxNo: (result?.invoiceTaxNo as string) || '',
      }

      message.success('登录成功!')

      setTimeout(() => {
        if (isVip) {
          // 已充值 -> 会员权益页
          navigate('/member-valid', {
            state: memberInfo,
          })
        } else {
          // 未充值 -> 支付页
          navigate('/payment', {
            state: {
              ...memberInfo,
              isRenew: false,
            },
          })
        }
      }, 500)
    } catch (error) {
      // 请求拦截器已统一 message.error,这里不重复提示
      console.error('[个人会员登录] 失败:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleRegister = () => {
    navigate('/register')
  }

  return (
    <div className="login-page">
      <div className="login-header">
        <Button 
          type="text" 
          icon={<ArrowLeftOutlined />} 
          onClick={() => navigate('/')}
          className="back-btn"
        />
        <h1 className="login-title">个人会员登入</h1>
      </div>

      <div className="login-form-container">
        <Card className="login-card" bordered={false}>
          <Form
            layout="vertical"
            onFinish={onFinish}
            size="large"
            initialValues={{
              // 与个人会员注册默认字段保持一致,方便联调调试
              phone: '13800000001',
              password: '123456'
            }}
          >
            <Form.Item
              name="phone"
              rules={[
                { required: true, message: '请输入手机号' },
                { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
              ]}
            >
              <Input 
                prefix={<UserOutlined />} 
                placeholder="请输入手机号" 
                maxLength={11}
              />
            </Form.Item>

            <Form.Item
              name="password"
              rules={[{ required: true, message: '请输入密码' }]}
            >
              <Input.Password 
                prefix={<LockOutlined />} 
                placeholder="请输入密码" 
              />
            </Form.Item>

            <Form.Item>
              <Button 
                type="primary" 
                htmlType="submit" 
                className="login-btn"
                loading={loading}
                block
              >
                登入
              </Button>
            </Form.Item>
          </Form>
        </Card>

        <Card className="register-card" bordered={false}>
          <p className="register-text">还没有账号?</p>
          <Button 
            type="default" 
            className="register-btn"
            onClick={handleRegister}
            block
          >
            立即注册
          </Button>
        </Card>
      </div>
    </div>
  )
}

export default PersonalLogin
