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

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

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

      // 保存 token (存在则存)
      // 保存后端返回的 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: 999.0,
        validPeriod: '1年',
      }

      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('/company-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: '13900139000',
              password: '123456'
            }}
          >
            <Form.Item
              name="phone"
              rules={[
                { required: true, message: '请输入手机号' },
                { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
              ]}
            >
              <Input 
                prefix={<BankOutlined />} 
                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 CompanyLogin
