import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Button, Form, Input, message, Select } from 'antd'
import { getBrands, login, BrandVO } from '../../api/auth'
import { setCredentials } from '../../store/slices/authSlice'
import { useAppDispatch } from '../../store/hooks'

export default function LoginPage() {
  const [brandOptions, setBrandOptions] = useState<BrandVO[]>([])
  const [loading, setLoading] = useState(false)
  const [form] = Form.useForm()
  const dispatch = useAppDispatch()
  const navigate = useNavigate()

  useEffect(() => {
    getBrands().then(brands => {
      setBrandOptions(brands)
      const std = brands.find(b => b.sName === '标准版')
      const defaultNo = std ? std.sNo : brands[0]?.sNo
      if (defaultNo) form.setFieldValue('brandNo', defaultNo)
    }).catch(() => {})
  }, [])

  const onFinish = async (values: { brandNo: string; username: string; password: string }) => {
    setLoading(true)
    try {
      const result = await login(values)
      dispatch(setCredentials({
        accessToken: result.accessToken,
        refreshToken: result.refreshToken,
        userInfo: result.userInfo
      }))
      navigate('/')
    } catch (e: unknown) {
      message.error(e instanceof Error ? e.message : '登录失败')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '100vh' }}>
      <div style={{ width: 360 }}>
        <h2 style={{ textAlign: 'center', marginBottom: 24 }}>小羚羊 ERP</h2>
        <Form form={form} layout="vertical" onFinish={onFinish}>
          <Form.Item label="公司/版本" name="brandNo" rules={[{ required: true, message: '请选择公司/版本' }]}>
            <Select
              options={brandOptions.map(b => ({ value: b.sNo, label: b.sName }))}
              placeholder="请选择公司/版本"
            />
          </Form.Item>
          <Form.Item label="用户名" name="username" rules={[{ required: true, message: '请输入用户名' }]}>
            <Input placeholder="请输入用户名" />
          </Form.Item>
          <Form.Item label="密码" name="password" rules={[{ required: true, message: '请输入密码' }]}>
            <Input.Password placeholder="请输入密码" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading} block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
