import { Button, Card, Form, Input, message, Typography } from 'antd'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'

import apiClient, { isEnvelope } from '../../api/client'
import type { SessionUser } from '../../stores/auth'

interface Props {
  onLogin: (u: SessionUser) => void
}

interface LoginValues {
  email: string
  password: string
}

export default function LoginPage({ onLogin }: Props) {
  const { t } = useTranslation()
  const navigate = useNavigate()

  const onFinish = async (vals: LoginValues) => {
    try {
      const r = await apiClient.post('/auth/login', vals)
      if (isEnvelope(r.data)) {
        const u = r.data.data as SessionUser
        onLogin(u)
        navigate('/dashboard', { replace: true })
        return
      }
    } catch (e: unknown) {
      const err = e as { message?: string; status?: number }
      if (err.status === 503) {
        // setup-mode → drop to wizard
        navigate('/setup', { replace: true })
        return
      }
      message.error(err.message ?? t('auth.loginFailed'))
    }
  }

  return (
    <div style={{ display: 'flex', minHeight: '100vh', alignItems: 'center', justifyContent: 'center', background: '#f0f2f5' }}>
      <Card style={{ width: 400 }}>
        <Typography.Title level={3} style={{ textAlign: 'center', marginBottom: 24 }}>
          {t('app.title')}
        </Typography.Title>
        <Form layout="vertical" onFinish={onFinish}>
          <Form.Item
            label={t('auth.email')}
            name="email"
            rules={[{ required: true, type: 'email' }]}
          >
            <Input autoComplete="email" autoFocus />
          </Form.Item>
          <Form.Item
            label={t('auth.password')}
            name="password"
            rules={[{ required: true }]}
          >
            <Input.Password autoComplete="current-password" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" block>
              {t('auth.login')}
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
