import { useCallback, useEffect, useRef, useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { ArrowLeftOutlined, MailOutlined } from '@ant-design/icons'
import { Button, Form, Input, Result, Spin, Typography, message } from 'antd'

import { AuthLayout } from '@/layouts'
import { getErrorMessage } from '@/lib/errors'
import {
  activateEmail,
  getAuthCapabilities,
  resendActivationEmail,
} 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 ResendFormValues = {
  email: string
}

export function ActivateAccountPage() {
  const [form] = Form.useForm<ResendFormValues>()
  const [searchParams] = useSearchParams()
  const token = searchParams.get('token')?.trim() ?? ''
  const initialEmail = searchParams.get('email')?.trim() ?? ''

  const [loading, setLoading] = useState(Boolean(token))
  const [capabilities, setCapabilities] = useState<AuthCapabilities>(DEFAULT_CAPABILITIES)
  const [capabilitiesLoaded, setCapabilitiesLoaded] = useState(false)
  const [activated, setActivated] = useState(false)
  const [activationError, setActivationError] = useState('')
  const [resending, setResending] = useState(false)
  const [resentEmail, setResentEmail] = useState<string | null>(null)
  const activatedTokenRef = useRef<string | null>(null)
  const activationRequestRef = useRef<Promise<void> | null>(null)

  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
    }
  }, [])

  useEffect(() => {
    if (!token) {
      setLoading(false)
      return
    }
    if (activatedTokenRef.current === token && activationRequestRef.current) {
      return
    }
    activatedTokenRef.current = token
    setActivationError('')
    setActivated(false)
    setLoading(true)

    const runActivation = (async () => {
      try {
        await activateEmail(token)
        setActivated(true)
      } catch (error) {
        setActivationError(getErrorMessage(error, '激活失败，请稍后重试'))
      } finally {
        setLoading(false)
      }
    })()

    activationRequestRef.current = runActivation
    void runActivation
  }, [token])

  const handleResend = useCallback(async (values: ResendFormValues) => {
    const email = values.email.trim()
    setResending(true)
    try {
      const result = await resendActivationEmail({ email })
      setResentEmail(email)
      message.success(result.message || '激活邮件已发送，请检查邮箱')
    } catch (error) {
      message.error(getErrorMessage(error, '激活邮件发送失败，请稍后重试'))
    } finally {
      setResending(false)
    }
  }, [])

  if (loading) {
    return (
      <AuthLayout>
        <div style={{ textAlign: 'center', padding: '48px 0' }}>
          <Spin size="large" />
          <Paragraph type="secondary" style={{ marginTop: 16 }}>
            正在验证激活链接...
          </Paragraph>
        </div>
      </AuthLayout>
    )
  }

  if (activated) {
    return (
      <AuthLayout>
        <Result
          status="success"
          title="邮箱验证成功"
          subTitle="您的账号已激活，现在可以返回登录页面正常使用。"
          extra={[
            <Link key="login" to="/login">
              <Button type="primary">立即登录</Button>
            </Link>,
          ]}
        />
      </AuthLayout>
    )
  }

  const emailActivationEnabled = capabilities.email_activation
  const resultStatus = token
    ? 'error'
    : capabilitiesLoaded && !emailActivationEnabled
      ? 'warning'
      : 'info'
  const resultTitle = token
    ? '激活链接不可用'
    : capabilitiesLoaded && !emailActivationEnabled
      ? '邮箱激活未启用'
      : '重新发送激活邮件'
  const resultSubtitle = token
    ? activationError || '当前激活链接无效、已过期或已被使用。'
    : capabilitiesLoaded && !emailActivationEnabled
      ? '当前环境未配置可用的邮件投递能力，无法重新发送激活邮件。'
      : '请输入注册邮箱，我们会重新发送激活链接。'

  return (
    <AuthLayout>
      <Result
        status={resultStatus}
        title={resultTitle}
        subTitle={resultSubtitle}
        extra={[
          <Link key="login" to="/login">
            <Button type="primary">返回登录</Button>
          </Link>,
          <Link key="register" to="/register">
            <Button>创建账号</Button>
          </Link>,
        ]}
      />

      {emailActivationEnabled && (
        <div style={{ maxWidth: 420, margin: '0 auto' }}>
          <Title level={5} style={{ marginBottom: 8 }}>
            重发激活邮件
          </Title>
          <Paragraph type="secondary" style={{ marginBottom: 24 }}>
            输入注册邮箱后，系统会重新发送新的激活链接。
          </Paragraph>

          {resentEmail && (
            <Paragraph style={{ marginBottom: 16 }}>
              已向 <Text strong>{resentEmail}</Text> 发送新的激活邮件，请检查收件箱和垃圾邮件目录。
            </Paragraph>
          )}

          <Form<ResendFormValues>
            form={form}
            layout="vertical"
            initialValues={{ email: initialEmail }}
            onFinish={handleResend}
            autoComplete="off"
          >
            <Form.Item
              name="email"
              rules={[
                { required: true, message: '请输入邮箱地址' },
                { type: 'email', message: '请输入有效的邮箱地址' },
              ]}
            >
              <Input
                prefix={<MailOutlined />}
                placeholder="邮箱地址"
                size="large"
                autoComplete="email"
              />
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit" size="large" block loading={resending}>
                重新发送激活邮件
              </Button>
            </Form.Item>
          </Form>

          <div style={{ textAlign: 'center', marginTop: 16 }}>
            <Link to="/login">
              <Text type="secondary">
                <ArrowLeftOutlined style={{ marginRight: 4 }} />
                返回登录
              </Text>
            </Link>
          </div>
        </div>
      )}
    </AuthLayout>
  )
}
