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

import { AuthLayout } from '@/layouts'
import { getErrorMessage } from '@/lib/errors'
import { forgotPassword, getAuthCapabilities } from '@/services/auth'

const { Paragraph, Text, Title } = Typography

type ForgotPasswordFormValues = {
  email: string
}

export function ForgotPasswordPage() {
  const [loading, setLoading] = useState(false)
  const [submitted, setSubmitted] = useState(false)
  const [submittedEmail, setSubmittedEmail] = useState('')
  const [passwordResetEnabled, setPasswordResetEnabled] = useState(false)
  const [capabilitiesLoaded, setCapabilitiesLoaded] = useState(false)

  useEffect(() => {
    let cancelled = false

    const loadCapabilities = async () => {
      try {
        const result = await getAuthCapabilities()
        if (!cancelled) {
          setPasswordResetEnabled(result.password_reset)
        }
      } catch {
        if (!cancelled) {
          setPasswordResetEnabled(false)
        }
      } finally {
        if (!cancelled) {
          setCapabilitiesLoaded(true)
        }
      }
    }

    void loadCapabilities()

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

  const handleSubmit = useCallback(async (values: ForgotPasswordFormValues) => {
    setLoading(true)
    try {
      await forgotPassword({ email: values.email })
      setSubmittedEmail(values.email)
      setSubmitted(true)
      message.success('重置邮件已发送')
    } catch (error) {
      message.error(getErrorMessage(error, '发送失败，请稍后重试'))
    } finally {
      setLoading(false)
    }
  }, [])

  if (capabilitiesLoaded && !passwordResetEnabled) {
    return (
      <AuthLayout>
        <Result
          status="warning"
          title="密码重置未启用"
          subTitle="当前运行环境未配置可用的邮件发送能力，密码重置入口已关闭。"
          extra={[
            <Link key="login" to="/login">
              <Button type="primary">返回登录</Button>
            </Link>,
          ]}
        />
      </AuthLayout>
    )
  }

  if (submitted) {
    return (
      <AuthLayout>
        <Result
          status="success"
          title="邮件已发送"
          subTitle={(
            <Paragraph>
              我们已向 <Text strong>{submittedEmail}</Text> 发送密码重置链接，请检查收件箱和垃圾邮件目录。
            </Paragraph>
          )}
          extra={[
            <Link key="login" to="/login">
              <Button type="primary">返回登录</Button>
            </Link>,
          ]}
        />
      </AuthLayout>
    )
  }

  return (
    <AuthLayout>
      <Title level={3} style={{ marginBottom: 8 }}>
        忘记密码
      </Title>
      <Paragraph type="secondary" style={{ marginBottom: 24 }}>
        输入您的邮箱地址，系统将向您发送密码重置链接。
      </Paragraph>

      <Form<ForgotPasswordFormValues> layout="vertical" onFinish={handleSubmit} 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={loading}>
            发送重置链接
          </Button>
        </Form.Item>
      </Form>

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