'use client';

import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { useState, useMemo } from 'react';
import { useAuthStore } from '@/stores/auth-store';
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 register schema with translated messages
 * VI: Tạo register schema với thông báo đã dịch
 */
function createRegisterSchema(t: (key: string) => string) {
  return z
    .object({
      fullName: z
        .string()
        .min(1, t('validation.fullNameRequired'))
        .min(2, t('validation.fullNameMin'))
        .max(100, t('validation.fullNameMax')),
      email: z
        .string()
        .min(1, t('validation.emailRequired'))
        .email(t('validation.email')),
      password: z
        .string()
        .min(1, t('validation.password'))
        .min(8, t('validation.passwordMin'))
        .regex(/[A-Z]/, t('validation.passwordUppercase'))
        .regex(/[a-z]/, t('validation.passwordLowercase'))
        .regex(/[0-9]/, t('validation.passwordNumber'))
        .regex(/[^A-Za-z0-9]/, t('validation.passwordSpecial')),
      confirmPassword: z
        .string()
        .min(1, t('validation.passwordConfirmRequired')),
      terms: z.boolean().refine((val) => val === true, {
        message: t('validation.termsRequired'),
      }),
    })
    .refine((data) => data.password === data.confirmPassword, {
      message: t('validation.passwordConfirm'),
      path: ['confirmPassword'],
    });
}


/**
 * EN: Password strength levels
 * VI: Các mức độ mạnh của mật khẩu
 */
type PasswordStrength = 'weak' | 'fair' | 'good' | 'strong';

/**
 * EN: Calculate password strength based on criteria
 * VI: Tính toán độ mạnh mật khẩu dựa trên các tiêu chí
 *
 * @param password - Password to evaluate / Mật khẩu cần đánh giá
 * @returns Password strength level / Mức độ mạnh mật khẩu
 */
function calculatePasswordStrength(password: string): {
  strength: PasswordStrength;
  percentage: number;
  feedback: string;
} {
  if (!password) {
    return { strength: 'weak', percentage: 0, feedback: '' };
  }

  let score = 0;
  const checks = {
    length: password.length >= 8,
    uppercase: /[A-Z]/.test(password),
    lowercase: /[a-z]/.test(password),
    number: /[0-9]/.test(password),
    special: /[^A-Za-z0-9]/.test(password),
  };

  // EN: Calculate score based on criteria / VI: Tính điểm dựa trên tiêu chí
  if (checks.length) score += 20;
  if (checks.uppercase) score += 20;
  if (checks.lowercase) score += 20;
  if (checks.number) score += 20;
  if (checks.special) score += 20;

  // EN: Additional points for length / VI: Điểm thêm cho độ dài
  if (password.length >= 12) score += 10;
  if (password.length >= 16) score += 10;

  // EN: Cap at 100% / VI: Giới hạn ở 100%
  score = Math.min(score, 100);

  let strength: PasswordStrength;
  let feedback: string;

  // EN: This will be translated in the component / VI: Sẽ được dịch trong component
  if (score < 25) {
    strength = 'weak';
    feedback = 'weak';
  } else if (score < 50) {
    strength = 'fair';
    feedback = 'fair';
  } else if (score < 75) {
    strength = 'good';
    feedback = 'good';
  } else {
    strength = 'strong';
    feedback = 'strong';
  }

  return { strength, percentage: score, feedback };
}

/**
 * EN: Register page component for user registration
 * VI: Component trang đăng ký để đăng ký người dùng
 *
 * Features:
 * - Full name, email, password, confirm password inputs
 * - Password strength indicator with visual feedback
 * - Terms & conditions checkbox
 * - Real-time validation
 * - Error handling
 */
export default function RegisterPage() {
  // EN: Translation hook / VI: Hook translation
  const { t } = useTranslation();

  // EN: Next.js router for navigation
  // VI: Next.js router để điều hướng
  const router = useRouter();

  // EN: Auth store hooks for registration functionality
  // VI: Auth store hooks cho chức năng đăng ký
  const { register: registerUser, isLoading } = useAuthStore();

  // 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 registerSchema = createRegisterSchema(t);
  type RegisterFormData = z.infer<typeof registerSchema>;

  // EN: React Hook Form setup with Zod resolver
  // VI: Setup React Hook Form với Zod resolver
  const {
    register,
    handleSubmit,
    watch,
    formState: { errors, isSubmitting },
  } = useForm<RegisterFormData>({
    resolver: zodResolver(registerSchema),
    defaultValues: {
      fullName: '',
      email: '',
      password: '',
      confirmPassword: '',
      terms: false,
    },
  });

  // EN: Watch password field for strength calculation
  // VI: Theo dõi trường password để tính độ mạnh
  const password = watch('password');

  // EN: Calculate password strength
  // VI: Tính toán độ mạnh mật khẩu
  const passwordStrength = useMemo(
    () => calculatePasswordStrength(password || ''),
    [password]
  );

  /**
   * EN: Handle form submission for registration
   * VI: Xử lý submit form để đăng ký
   *
   * @param data - Form data validated by Zod / Dữ liệu form đã được validate bởi Zod
   * Note: fullName is collected for UX but not sent to API (backend generates username from email)
   * Ghi chú: fullName được thu thập cho UX nhưng không gửi đến API (backend tạo username từ email)
   */
  const onSubmit = async (data: RegisterFormData) => {
    setApiError('');
    try {
      // EN: Attempt registration through auth store
      // VI: Thử đăng ký thông qua auth store
      // Note: RegisterDto only accepts email, password, confirmPassword
      // Ghi chú: RegisterDto chỉ chấp nhận email, password, confirmPassword
      await registerUser(data.email, data.password, data.confirmPassword);
      // EN: Redirect to home page on successful registration
      // VI: Chuyển hướng về trang chủ khi đăng ký thành công
      router.push('/');
    } 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('auth.register.registrationFailed'));
    }
  };

  // EN: Get color for password strength indicator
  // VI: Lấy màu cho chỉ báo độ mạnh mật khẩu
  const getStrengthColor = (strength: PasswordStrength) => {
    switch (strength) {
      case 'weak':
        return 'bg-accent-error'; // Red
      case 'fair':
        return 'bg-accent-warning'; // Amber
      case 'good':
        return 'bg-accent-warning'; // Yellow (using warning for good)
      case 'strong':
        return 'bg-accent-success'; // Green
      default:
        return 'bg-border-primary';
    }
  };

  return (
    // EN: Centered register form layout with dark mode background
    // VI: Layout form đăng ký đượ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.register.createAccount')}
          </CardTitle>
          <CardDescription className="mt-2">
            {t('auth.register.signUpToStart')}
          </CardDescription>
        </CardHeader>

        <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: Full name input field / VI: Trường nhập họ tên */}
            <Input
              type="text"
              label={t('auth.register.fullName')}
              placeholder="John Doe"
              validationState={errors.fullName ? 'error' : 'default'}
              errorMessage={errors.fullName?.message}
              {...register('fullName')}
              autoComplete="name"
              aria-required="true"
            />

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

            {/* EN: Password input field / VI: Trường nhập mật khẩu */}
            <div>
              <Input
                type="password"
                label={t('auth.register.password')}
                placeholder={t('auth.register.createStrongPassword')}
                validationState={errors.password ? 'error' : 'default'}
                errorMessage={errors.password?.message}
                {...register('password')}
                autoComplete="new-password"
                aria-required="true"
              />

              {/* EN: Password strength indicator / VI: Chỉ báo độ mạnh mật khẩu */}
              {password && (
                <div className="mt-2 space-y-2">
                  {/* EN: Strength bar / VI: Thanh độ mạnh */}
                  <div className="w-full h-2 bg-bg-tertiary rounded-full overflow-hidden">
                    <div
                      className={`h-full transition-all duration-300 ${getStrengthColor(
                        passwordStrength.strength
                      )}`}
                      style={{ width: `${passwordStrength.percentage}%` }}
                      role="progressbar"
                      aria-valuenow={passwordStrength.percentage}
                      aria-valuemin={0}
                      aria-valuemax={100}
                      aria-label={t('auth.register.passwordStrength', { strength: t(`auth.register.${passwordStrength.feedback}`) })}
                    />
                  </div>

                  {/* EN: Strength feedback text / VI: Text phản hồi độ mạnh */}
                  <p
                    className={`text-xs font-medium ${
                      passwordStrength.strength === 'weak'
                        ? 'text-accent-error'
                        : passwordStrength.strength === 'fair'
                        ? 'text-accent-warning'
                        : passwordStrength.strength === 'good'
                        ? 'text-accent-warning'
                        : 'text-accent-success'
                    }`}
                  >
                    {t(`auth.register.${passwordStrength.feedback}`)}
                  </p>
                </div>
              )}
            </div>

            {/* EN: Confirm password input field / VI: Trường xác nhận mật khẩu */}
            <Input
              type="password"
              label={t('auth.register.confirmPassword')}
              placeholder={t('auth.register.reEnterPassword')}
              validationState={errors.confirmPassword ? 'error' : 'default'}
              errorMessage={errors.confirmPassword?.message}
              {...register('confirmPassword')}
              autoComplete="new-password"
              aria-required="true"
            />

            {/* EN: Terms and conditions checkbox / VI: Checkbox điều khoản và điều kiện */}
            <div className="space-y-2">
              <label className="flex items-start gap-2 cursor-pointer group">
                <input
                  type="checkbox"
                  {...register('terms')}
                  className="mt-1 w-4 h-4 rounded border-border-primary bg-bg-secondary text-accent-primary focus:ring-2 focus:ring-accent-primary focus:ring-offset-2 focus:ring-offset-bg-primary cursor-pointer flex-shrink-0"
                  aria-required="true"
                  aria-invalid={errors.terms ? 'true' : 'false'}
                />
                <span className="text-sm text-text-secondary group-hover:text-text-primary transition-colors">
                  {t('auth.register.agreeToTerms')}{' '}
                  <Link
                    href="/terms"
                    className="text-accent-primary hover:brightness-110 underline focus:outline-none focus:ring-2 focus:ring-accent-primary focus:ring-offset-2 focus:ring-offset-bg-primary rounded"
                    target="_blank"
                    rel="noopener noreferrer"
                  >
                    {t('auth.register.termsAndConditions')}
                  </Link>
                </span>
              </label>
              {errors.terms && (
                <p className="text-sm text-accent-error flex items-center gap-1 ml-6" role="alert">
                  <svg
                    className="h-4 w-4"
                    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>
                  {errors.terms.message}
                </p>
              )}
            </div>
          </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={isLoading || isSubmitting}
              disabled={isLoading || isSubmitting}
            >
              {isLoading || isSubmitting
                ? t('auth.register.creatingAccount')
                : t('auth.register.createAccount')}
            </Button>

            {/* EN: Sign in link / VI: Link đăng nhập */}
            <p className="text-sm text-center text-text-tertiary">
              {t('auth.register.alreadyHaveAccount')}{' '}
              <Link
                href="/login"
                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.register.signIn')}
              </Link>
            </p>
          </CardFooter>
        </form>
      </Card>
    </div>
  );
}
