'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 '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from '@/components/ui/card';
import { useTranslation } from '@/hooks/use-translation';

/**
 * 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 } = useTranslation();

  // 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,
    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 dark mode background
    // VI: Layout form quên mật khẩu được căn giữa với nền dark mode
    <div className="min-h-screen flex items-center justify-center bg-bg-primary px-4 py-12">
      <Card className="w-full max-w-md" hover={false} bordered>
        <CardHeader className="text-center">
          <CardTitle className="text-2xl font-semibold">
            {t('auth.forgotPassword.title')}
          </CardTitle>
          <CardDescription className="mt-2">
            {isSuccess
              ? t('auth.forgotPassword.checkEmail')
              : t('auth.forgotPassword.description')}
          </CardDescription>
        </CardHeader>

        {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
          <CardContent className="space-y-4">
            {/* EN: Success icon and message / VI: Icon và thông báo thành công */}
            <div
              className="p-4 rounded-lg bg-bg-tertiary border border-accent-success text-accent-success flex items-center gap-3"
              role="alert"
            >
              <svg
                className="h-5 w-5 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-medium">
                {t('auth.forgotPassword.resetLinkSent')}
              </span>
            </div>

            {/* EN: Detailed success message / VI: Thông báo thành công chi tiết */}
            <div className="space-y-3 text-sm text-text-secondary">
              <p>
                {t('auth.forgotPassword.resetLinkSentDetail', { email: submittedEmail })}
              </p>
              <div className="pt-2 border-t border-border-primary">
                <p className="text-text-tertiary">
                  {t('auth.forgotPassword.checkInbox')}
                </p>
              </div>
            </div>

            {/* EN: Additional action buttons / VI: Các nút hành động bổ sung */}
            <div className="pt-2 space-y-2">
              <Button
                variant="ghost"
                size="sm"
                className="w-full"
                onClick={() => {
                  setIsSuccess(false);
                  setSubmittedEmail('');
                }}
              >
                {t('auth.forgotPassword.sendToAnotherEmail')}
              </Button>
            </div>
          </CardContent>
        ) : (
          // EN: Form state - email input and submit
          // VI: Trạng thái form - input email và submit
          <form onSubmit={handleSubmit(onSubmit)}>
            <CardContent className="space-y-4">
              {/* EN: API Error message display / VI: Hiển thị thông báo lỗi API */}
              {apiError && (
                <div
                  className="p-3 rounded-md bg-bg-tertiary border border-accent-error text-accent-error text-sm flex items-center gap-2"
                  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>
              )}

              {/* EN: Email input field / VI: Trường nhập email */}
              <Input
                type="email"
                label={t('auth.forgotPassword.email')}
                placeholder="you@example.com"
                validationState={errors.email ? 'error' : 'default'}
                errorMessage={errors.email?.message}
                {...register('email')}
                autoComplete="email"
                autoFocus
                aria-required="true"
              />
            </CardContent>

            <CardFooter className="flex flex-col gap-4">
              {/* EN: Submit button with loading state / VI: Nút submit với trạng thái loading */}
              <Button
                type="submit"
                variant="primary"
                size="lg"
                className="w-full"
                loading={isSubmitting}
                disabled={isSubmitting}
              >
                {isSubmitting
                  ? t('auth.forgotPassword.sending')
                  : t('auth.forgotPassword.sendResetLink')}
              </Button>
            </CardFooter>
          </form>
        )}

        <CardFooter className="flex flex-col gap-2 pt-4">
          {/* EN: Back to login link / VI: Link quay lại đăng nhập */}
          <Link
            href="/login"
            className="text-sm text-accent-primary hover:brightness-110 transition-colors focus:outline-none focus:ring-2 focus:ring-accent-primary focus:ring-offset-2 focus:ring-offset-bg-primary rounded"
          >
            ← {t('auth.forgotPassword.backToLogin')}
          </Link>

          {/* EN: Sign up link / VI: Link đăng ký */}
          <p className="text-sm text-center text-text-tertiary">
            {t('auth.forgotPassword.noAccount')}{' '}
            <Link
              href="/register"
              className="text-accent-primary hover:brightness-110 font-medium transition-colors focus:outline-none focus:ring-2 focus:ring-accent-primary focus:ring-offset-2 focus:ring-offset-bg-primary rounded"
            >
              {t('auth.forgotPassword.signUp')}
            </Link>
          </p>
        </CardFooter>
      </Card>
    </div>
  );
}
