'use client';

import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import Link from 'next/link';
import { useState } from 'react';
import { authApi } from '@/services/api/auth.api';
import { Button } from '@/features/shared/components/ui/button';
import { Input } from '@/features/shared/components/ui/input';
import { useTranslations } from 'next-intl';
import { AuthControls } from '@/features/shared/components/layout/auth-controls';

/**
 * EN: Create forgot password schema with translated messages
 * VI: Tạo forgot password schema với thông báo đã dịch
 */
function createForgotPasswordSchema(t: (key: string) => string) {
  return z.object({
    email: z
      .string()
      .min(1, t('validation.emailRequired'))
      .email(t('validation.email')),
  });
}


/**
 * EN: Forgot Password page component - allows users to request password reset link
 * VI: Component trang quên mật khẩu - cho phép người dùng yêu cầu link đặt lại mật khẩu
 *
 * Features:
 * - Email input with real-time validation
 * - Error messages below inputs
 * - Loading state on button
 * - Success state with confirmation message
 * - Link to check email
 * - Back to login link
 *
 * Flow:
 * 1. Enter email → Send reset link
 * 2. Check email → Click link
 * 3. Enter new password → Confirm
 * 4. Success → Redirect to login
 */
export default function ForgotPasswordPage() {
  // EN: Translation hook / VI: Hook translation
  const t = useTranslations();

  // EN: Success state - shows confirmation after email is sent
  // VI: Trạng thái thành công - hiển thị xác nhận sau khi email được gửi
  const [isSuccess, setIsSuccess] = useState(false);
  const [submittedEmail, setSubmittedEmail] = useState('');

  // EN: General error state for API errors
  // VI: Trạng thái lỗi chung cho lỗi API
  const [apiError, setApiError] = useState<string>('');

  // EN: Create schema with translations / VI: Tạo schema với translations
  const forgotPasswordSchema = createForgotPasswordSchema(t);
  type ForgotPasswordFormData = z.infer<typeof forgotPasswordSchema>;

  // EN: React Hook Form setup with Zod resolver
  // VI: Setup React Hook Form với Zod resolver
  const {
    register,
    handleSubmit,
    setValue,
    formState: { errors, isSubmitting },
  } = useForm<ForgotPasswordFormData>({
    resolver: zodResolver(forgotPasswordSchema),
    defaultValues: {
      email: '',
    },
  });

  /**
   * EN: Handle form submission for forgot password
   * VI: Xử lý submit form để quên mật khẩu
   *
   * @param data - Form data validated by Zod / Dữ liệu form đã được validate bởi Zod
   */
  const onSubmit = async (data: ForgotPasswordFormData) => {
    setApiError('');
    try {
      // EN: Request password reset link via API
      // VI: Yêu cầu link đặt lại mật khẩu qua API
      const response = await authApi.forgotPassword(data.email);

      if (response.success) {
        // EN: Show success message and store email for display
        // VI: Hiển thị thông báo thành công và lưu email để hiển thị
        setIsSuccess(true);
        setSubmittedEmail(data.email);
      } else {
        setApiError(
          response.error?.message || t('auth.forgotPassword.failedToSend')
        );
      }
    } catch (err: any) {
      // EN: Set error message from API response
      // VI: Đặt thông báo lỗi từ phản hồi API
      setApiError(err.message || t('errors.generic'));
    }
  };

  return (
    // EN: Centered forgot password form layout with cosmic background and glassmorphism
    // VI: Layout form quên mật khẩu với nền vũ trụ và hiệu ứng kínhmorphism
    <main
      role="main"
      aria-label={t('auth.forgotPassword.title')}
      className="min-h-screen flex items-center justify-center relative overflow-hidden bg-bg-primary py-12 px-4 sm:px-6 lg:px-8"
    >
      {/* EN: X.ai Minimal Design - No cosmic background */}
      {/* VI: X.ai Minimal Design - Không có nền vũ trụ */}

      <AuthControls />

      <div className="w-full max-w-md md:max-w-[400px] space-y-8 relative z-10 glass-appear">
        <div className="text-center space-y-4">
          <div className="flex justify-center">
            <div className="p-3 rounded-2xl bg-accent-primary/5 border border-accent-primary/10 shadow-glass-sm">
              {/* EN: X.ai Minimal - Static icon (no floating) */}
              {/* VI: X.ai Minimal - Icon tĩnh (không float) */}
              <svg
                width="40"
                height="40"
                viewBox="0 0 24 24"
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
                className="text-text-primary"
              >
                <path
                  d="M12 2L14.4 9.6H22L15.8 14.2L18.2 21.8L12 17.2L5.8 21.8L8.2 14.2L2 9.6H9.6L12 2Z"
                  fill="currentColor"
                />
              </svg>
            </div>
          </div>
          <h1 className="text-4xl font-bold tracking-tight text-text-primary mb-2">
            {t('auth.forgotPassword.title')}
          </h1>
          <p className="text-text-secondary">
            {isSuccess
              ? t('auth.forgotPassword.checkEmail')
              : t('auth.forgotPassword.description')}
          </p>
        </div>

        <div className="glass-card p-8 shadow-glass-xl border-border-primary">
          {isSuccess ? (
            // EN: Success state - show confirmation message
            // VI: Trạng thái thành công - hiển thị thông báo xác nhận
            <div className="space-y-6 animate-in fade-in zoom-in duration-500">
              <div
                className="p-4 rounded-xl bg-accent-success/10 border border-accent-success/20 text-accent-success flex items-center gap-3"
                role="alert"
              >
                <svg
                  className="h-6 w-6 flex-shrink-0"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                  aria-hidden="true"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M5 13l4 4L19 7"
                  />
                </svg>
                <span className="text-sm font-semibold">
                  {t('auth.forgotPassword.resetLinkSent')}
                </span>
              </div>

              <div className="space-y-4 text-sm text-text-secondary leading-relaxed">
                <p>
                  {t('auth.forgotPassword.resetLinkSentDetail', {
                    email: submittedEmail,
                  })}
                </p>
                <div className="pt-4 border-t border-glass-subtle">
                  <p className="text-text-tertiary">
                    {t('auth.forgotPassword.checkInbox')}
                  </p>
                </div>
              </div>

              <Button
                variant="brand"
                size="lg"
                className="w-full mt-4"
                onPress={() => (window.location.href = '/login')}
              >
                {t('auth.forgotPassword.backToLogin')}
              </Button>

              <button
                type="button"
                className="w-full text-sm text-text-tertiary hover:text-text-primary transition-colors"
                onClick={() => {
                  setIsSuccess(false);
                  setSubmittedEmail('');
                }}
              >
                {t('auth.forgotPassword.sendToAnotherEmail')}
              </button>
            </div>
          ) : (
            // EN: Form state - email input and submit
            // VI: Trạng thái form - input email và submit
            <form className="space-y-6" onSubmit={handleSubmit(onSubmit)}>
              {/* EN: API Error message display / VI: Hiển thị thông báo lỗi API */}
              {apiError && (
                <div
                  className="p-3 rounded-lg bg-accent-error/10 border border-accent-error/20 text-accent-error text-sm flex items-center gap-2 animate-in fade-in duration-quick"
                  role="alert"
                >
                  <svg
                    className="h-4 w-4 flex-shrink-0"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                    aria-hidden="true"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
                    />
                  </svg>
                  <span>{apiError}</span>
                </div>
              )}

              <Input
                type="email"
                variant="solid"
                label={t('auth.forgotPassword.email')}
                placeholder="you@example.com"
                isInvalid={!!errors.email}
                errorMessage={errors.email?.message}
                name={register('email').name}
                onBlur={register('email').onBlur}
                onChange={(value) => {
                  // EN: React Aria onChange receives value string, not event
                  // VI: React Aria onChange nhận value string, không phải event
                  setValue('email', value);
                }}
                autoComplete="email"
                autoFocus
                aria-required="true"
              />

              <Button
                type="submit"
                variant="brand"
                size="lg"
                className="w-full mt-4"
                isLoading={isSubmitting}
                isDisabled={isSubmitting}
              >
                {isSubmitting
                  ? t('auth.forgotPassword.sending')
                  : t('auth.forgotPassword.sendResetLink')}
              </Button>

              <div className="text-center pt-4 border-t border-border-primary/50">
                <Link
                  href="/login"
                  className="inline-flex items-center justify-center gap-2 px-6 py-2.5 rounded-xl border border-border-primary bg-bg-secondary text-sm font-semibold text-text-primary hover:bg-bg-tertiary hover:border-border-secondary transition-all group"
                >
                  <svg
                    className="h-4 w-4 transform group-hover:-translate-x-1 transition-transform"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M15 19l-7-7 7-7"
                    />
                  </svg>
                  {t('auth.forgotPassword.backToLogin')}
                </Link>
              </div>
            </form>
          )}
        </div>
      </div>
    </main>
  );
}
