import { LockOutlined, UserOutlined } from '@ant-design/icons'
import { Button, Card, Form, Input, Spin, Tabs, Typography, message } from 'antd'
import axios from 'axios'
import { useEffect, useState } from 'react'
import { Navigate, useNavigate } from 'react-router-dom'
import { settingsApi } from '../api/client'
import { useAuth } from '../context/AuthContext'

function apiErrorMessage(error: unknown, fallback: string) {
  if (axios.isAxiosError(error)) {
    const detail = error.response?.data?.detail
    if (typeof detail === 'string') return detail
    if (Array.isArray(detail) && detail[0]?.msg) return detail[0].msg
  }
  return fallback
}

export default function LoginPage() {
  const { user, login, register, loading } = useAuth()
  const navigate = useNavigate()
  const [loginForm] = Form.useForm()
  const [registerForm] = Form.useForm()
  const [registrationEnabled, setRegistrationEnabled] = useState(true)
  const [settingsLoading, setSettingsLoading] = useState(true)

  useEffect(() => {
    settingsApi
      .public()
      .then((res) => setRegistrationEnabled(res.data.registration_enabled))
      .catch(() => setRegistrationEnabled(true))
      .finally(() => setSettingsLoading(false))
  }, [])

  if (!loading && user) return <Navigate to="/" replace />

  const onLogin = async (values: { username: string; password: string }) => {
    try {
      await login(values.username, values.password)
      message.success('登录成功')
      navigate('/')
    } catch (error) {
      message.error(apiErrorMessage(error, '用户名或密码错误'))
    }
  }

  const onRegister = async (values: { username: string; password: string; confirm: string }) => {
    if (values.password !== values.confirm) {
      message.error('两次密码不一致')
      return
    }
    try {
      await register(values.username, values.password)
      message.success('注册成功')
      navigate('/')
    } catch (error) {
      message.error(apiErrorMessage(error, '注册失败，请稍后重试'))
    }
  }

  const tabItems = [
    {
      key: 'login',
      label: '登录',
      children: (
        <Form form={loginForm} onFinish={onLogin} layout="vertical">
          <Form.Item name="username" rules={[{ required: true, message: '请输入用户名' }]}>
            <Input prefix={<UserOutlined />} placeholder="用户名" />
          </Form.Item>
          <Form.Item name="password" rules={[{ required: true, message: '请输入密码' }]}>
            <Input.Password prefix={<LockOutlined />} placeholder="密码" />
          </Form.Item>
          <Button type="primary" htmlType="submit" block>
            登录
          </Button>
        </Form>
      ),
    },
  ]

  if (registrationEnabled) {
    tabItems.push({
      key: 'register',
      label: '注册',
      children: (
        <Form form={registerForm} onFinish={onRegister} layout="vertical">
          <Form.Item
            name="username"
            rules={[
              { required: true, message: '请输入用户名' },
              { min: 3, message: '至少3个字符' },
            ]}
          >
            <Input prefix={<UserOutlined />} placeholder="用户名" />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[
              { required: true, message: '请输入密码' },
              { min: 6, message: '至少6个字符' },
            ]}
          >
            <Input.Password prefix={<LockOutlined />} placeholder="密码" />
          </Form.Item>
          <Form.Item name="confirm" rules={[{ required: true, message: '请确认密码' }]}>
            <Input.Password prefix={<LockOutlined />} placeholder="确认密码" />
          </Form.Item>
          <Button type="primary" htmlType="submit" block>
            注册
          </Button>
        </Form>
      ),
    })
  }

  return (
    <div
      style={{
        minHeight: '100vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
        padding: 16,
      }}
    >
      <Card style={{ width: '100%', maxWidth: 420 }} title="中学生成绩档案">
        <Typography.Paragraph type="secondary" style={{ textAlign: 'center' }}>
          成绩录入 · 趋势分析 · 错题管理
        </Typography.Paragraph>
        <Spin spinning={settingsLoading}>
          {!settingsLoading && !registrationEnabled && (
            <Typography.Paragraph type="secondary" style={{ textAlign: 'center', marginBottom: 16 }}>
              注册已关闭，请联系管理员获取账号
            </Typography.Paragraph>
          )}
          <Tabs items={tabItems} />
        </Spin>
        <Typography.Paragraph
          type="secondary"
          style={{ textAlign: 'center', fontSize: 12, marginTop: 16, marginBottom: 0 }}
        >
          © 马建军 · 微信 dekun03 · 18364911125
        </Typography.Paragraph>
      </Card>
    </div>
  )
}
