import { useCallback, useEffect, useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { ArrowLeftOutlined, LockOutlined, MailOutlined, UserOutlined } from '@ant-design/icons'
import { Alert, Button, Form, Input, Result, Space, Typography, message } from 'antd'

import { useAuth } from '@/app/providers/auth-context'
import { AuthLayout } from '@/layouts'
import { getErrorMessage } from '@/lib/errors'
import { bootstrapAdmin, getAuthCapabilities } from '@/services/auth'
import type { AuthCapabilities } from '@/types'

const { Paragraph, Text, Title } = Typography

const DEFAULT_CAPABILITIES: AuthCapabilities = {
  password: true,
  email_activation: false,
  email_code: false,
  sms_code: false,
  password_reset: false,
  admin_bootstrap_required: false,
  oauth_providers: [],
}

type BootstrapAdminFormValues = {
  username: string
  nickname?: string
  email: string
  bootstrapSecret: string
  password: string
  confirmPassword: string
}

export function BootstrapAdminPage() {
  const [form] = Form.useForm<BootstrapAdminFormValues>()
  const [loading, setLoading] = useState(false)
  const [capabilities, setCapabilities] = useState<AuthCapabilities>(DEFAULT_CAPABILITIES)
  const [capabilitiesLoaded, setCapabilitiesLoaded] = useState(false)

  const { onLoginSuccess } = useAuth()
  const navigate = useNavigate()

  useEffect(() => {
    let cancelled = false

    const loadCapabilities = async () => {
      try {
        const result = await getAuthCapabilities()
        if (!cancelled) {
          setCapabilities(result)
        }
      } catch {
        if (!cancelled) {
          setCapabilities(DEFAULT_CAPABILITIES)
        }
      } finally {
        if (!cancelled) {
          setCapabilitiesLoaded(true)
        }
      }
    }

    void loadCapabilities()

    return () => {
      cancelled = true
    }
  }, [])

  const handleSubmit = useCallback(async (values: BootstrapAdminFormValues) => {
    setLoading(true)
    try {
      const tokenBundle = await bootstrapAdmin({
        username: values.username.trim(),
        nickname: values.nickname?.trim() || undefined,
        email: values.email!.trim(),
        bootstrap_secret: values.bootstrapSecret!.trim(),
        password: values.password,
      })
      await onLoginSuccess(tokenBundle)
      message.success('管理员初始化完成')
      navigate('/dashboard', { replace: true })
    } catch (error) {
      message.error(getErrorMessage(error, '管理员初始化失败，请检查输入信息后重试'))
    } finally {
      setLoading(false)
    }
  }, [navigate, onLoginSuccess])

  if (capabilitiesLoaded && !capabilities.admin_bootstrap_required) {
    return (
      <AuthLayout>
        <Result
          status="info"
          title="管理员已完成初始化"
          subTitle="系统已经存在可登录的管理员账号。请直接返回登录页，使用现有管理员账号进入系统。"
          extra={[
            <Link key="login" to="/login">
              <Button type="primary">返回登录</Button>
            </Link>,
            <Link key="register" to="/register">
              <Button>创建普通账号</Button>
            </Link>,
          ]}
        />
      </AuthLayout>
    )
  }

  return (
    <AuthLayout>
      <Title level={3} style={{ marginBottom: 8 }}>
        初始化首个管理员账号
      </Title>
      <Paragraph type="secondary" style={{ marginBottom: 24 }}>
        当前版本不内置默认账号。首次部署时，请提供 Bootstrap Secret 并创建首个管理员账号，初始化完成后系统会自动关闭该入口。
      </Paragraph>

      <Alert
        type="warning"
        showIcon
        message="该入口仅在系统没有可登录管理员时开放"
        description="初始化成功后，你会直接进入后台。后续管理员新增、禁用和权限调整应在系统内完成。"
        style={{ marginBottom: 24 }}
      />

      <Form<BootstrapAdminFormValues> form={form} layout="vertical" onFinish={handleSubmit} autoComplete="off">
        <Form.Item
          name="username"
          rules={[{ required: true, message: '请输入管理员用户名' }]}
        >
          <Input
            prefix={<UserOutlined />}
            placeholder="管理员用户名"
            size="large"
            autoComplete="username"
          />
        </Form.Item>
        <Form.Item name="nickname">
          <Input
            prefix={<UserOutlined />}
            placeholder="管理员昵称（选填）"
            size="large"
            autoComplete="nickname"
          />
        </Form.Item>
        <Form.Item
          name="email"
          rules={[
            { required: true, message: '请输入管理员邮箱' },
            { type: 'email', message: '请输入有效的邮箱地址' },
          ]}
        >
          <Input
            prefix={<MailOutlined />}
            placeholder="管理员邮箱"
            size="large"
            autoComplete="email"
          />
        </Form.Item>
        <Form.Item
          name="bootstrapSecret"
          rules={[{ required: true, message: '请输入 Bootstrap Secret' }]}
        >
          <Input.Password
            prefix={<LockOutlined />}
            placeholder="Bootstrap Secret"
            size="large"
            autoComplete="one-time-code"
          />
        </Form.Item>
        <Form.Item
          name="password"
          rules={[{ required: true, message: '请输入管理员密码' }]}
        >
          <Input.Password
            prefix={<LockOutlined />}
            placeholder="管理员密码"
            size="large"
            autoComplete="new-password"
          />
        </Form.Item>
        <Form.Item
          name="confirmPassword"
          dependencies={['password']}
          rules={[
            { required: true, message: '请再次输入管理员密码' },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('password') === value) {
                  return Promise.resolve()
                }
                return Promise.reject(new Error('两次输入的密码不一致'))
              },
            }),
          ]}
        >
          <Input.Password
            prefix={<LockOutlined />}
            placeholder="确认管理员密码"
            size="large"
            autoComplete="new-password"
          />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" size="large" block loading={loading}>
            完成初始化并进入系统
          </Button>
        </Form.Item>
      </Form>

      <div style={{ textAlign: 'center', marginTop: 16 }}>
        <Space split={<Text type="secondary">|</Text>}>
          <Link to="/login">
            <Text type="secondary">
              <ArrowLeftOutlined style={{ marginRight: 4 }} />
              返回登录
            </Text>
          </Link>
          <Link to="/register">
            <Text type="secondary">创建普通账号</Text>
          </Link>
        </Space>
      </div>
    </AuthLayout>
  )
}
