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 } 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)
      }

      // TODO: 待 yapi 返回字段明确后,调用 /member/status 查询会员状态决定跳转
      // 当前调试阶段,使用 mock 状态检查逻辑
      const memberStatus = {
        isPaid: result?.isPaid ?? false,
        isExpired: result?.isExpired ?? false,
        memberId: (result?.memberId as string) || 'MEM20260510001',
        memberType: '普通会员',
        amount: 99.0,
        validPeriod: '1年',
        expireDate: '2027-05-10',
      }

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

      // 根据会员状态跳转
      setTimeout(() => {
        if (!memberStatus.isPaid || memberStatus.isExpired) {
          // 未支付或已过期,跳转至待支付页面
          navigate('/payment', {
            state: {
              memberId: memberStatus.memberId,
              memberType: memberStatus.memberType,
              amount: memberStatus.amount,
              validPeriod: memberStatus.validPeriod,
              isRenew: memberStatus.isExpired,
            },
          })
        } else {
          // 会员有效,跳转至会员有效页面
          navigate('/member-valid', {
            state: {
              memberId: memberStatus.memberId,
              memberType: memberStatus.memberType,
              amount: memberStatus.amount,
              validPeriod: memberStatus.validPeriod,
            },
          })
        }
      }, 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: '13800138000',
              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
