/**
 * 重置密码页
 * 
 * 用户通过邮件中的链接访问此页面，输入新密码完成重置
 */

import { useState, useCallback, useEffect } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import {
  Form,
  Input,
  Button,
  Typography,
  message,
  Result,
  Spin,
} from 'antd'
import { LockOutlined, ArrowLeftOutlined } from '@ant-design/icons'
import { getErrorMessage } from '@/lib/errors'
import { AuthLayout } from '@/layouts'
import { validateResetToken, resetPassword } from '@/services/auth'

const { Title, Paragraph, Text } = Typography

type ResetPasswordFormValues = {
  password: string
  confirmPassword: string
}

type TokenValidation = {
  valid: boolean
  email?: string
  expiresAt?: string
}

export function ResetPasswordPage() {
  const [searchParams] = useSearchParams()
  const token = searchParams.get('token') || ''

  const [loading, setLoading] = useState(true)
  const [submitting, setSubmitting] = useState(false)
  const [submitted, setSubmitted] = useState(false)
  const [validation, setValidation] = useState<TokenValidation>({ valid: false })

  // 校验 token
  useEffect(() => {
    if (!token) {
      setLoading(false)
      return
    }

    const validateToken = async () => {
      try {
        const result = await validateResetToken(token)
        setValidation({
          valid: result.valid,
          email: result.email,
          expiresAt: result.expires_at,
        })
      } catch {
        setValidation({ valid: false })
      } finally {
        setLoading(false)
      }
    }

    validateToken()
  }, [token])

  const handleSubmit = useCallback(async (values: ResetPasswordFormValues) => {
    if (!token) {
      message.error('无效的重置链接')
      return
    }

    setSubmitting(true)
    try {
      await resetPassword({
        token,
        new_password: values.password,
        confirm_password: values.confirmPassword,
      })
      setSubmitted(true)
      message.success('密码重置成功')
    } catch (error) {
      message.error(getErrorMessage(error, '重置失败，请稍后重试'))
    } finally {
      setSubmitting(false)
    }
  }, [token])

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

  // 没有 token 或 token 无效
  if (!token || !validation.valid) {
    return (
      <AuthLayout>
        <Result
          status="error"
          title="链接无效"
          subTitle="该密码重置链接已失效或已过期，请重新申请重置密码。"
          extra={[
            <Link key="forgot" to="/forgot-password">
              <Button type="primary">重新申请</Button>
            </Link>,
            <Link key="login" to="/login">
              <Button>返回登录</Button>
            </Link>,
          ]}
        />
      </AuthLayout>
    )
  }

  // 重置成功
  if (submitted) {
    return (
      <AuthLayout>
        <Result
          status="success"
          title="密码已重置"
          subTitle="您的密码已成功重置，请使用新密码登录。"
          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 }}>
        为您的账号 <Text strong>{validation.email}</Text> 设置新密码
      </Paragraph>

      <Form<ResetPasswordFormValues>
        layout="vertical"
        onFinish={handleSubmit}
        autoComplete="off"
      >
        <Form.Item
          name="password"
          rules={[
            { required: true, message: '请输入新密码' },
            { min: 8, message: '密码至少 8 位' },
          ]}
        >
          <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={submitting}
          >
            确认重置
          </Button>
        </Form.Item>
      </Form>

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