'use client';

import { useForm, Controller } 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 '@/features/shared/components/ui/button';
import { Input } from '@/features/shared/components/ui/input';
import { AuthCard } from '@/features/auth/components/auth-card';
import { useTranslations } from 'next-intl';
import { AuthControls } from '@/features/shared/components/layout/auth-controls';
import { cn } from '@/shared/utils';

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

  // 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 {
    control,
    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('/dashboard');
    } 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 (
    <>
      <AuthControls />
      <AuthCard
        title={t('auth.register.createAccount')}
        description={t('auth.register.signUpToStart')}
        footer={
          <span>
            {t('auth.register.alreadyHaveAccount')}{' '}
            <Link
              href="/login"
              className="text-accent-primary hover:text-accent-primary-hover font-medium transition-colors"
            >
              {t('auth.register.signIn')}
            </Link>
          </span>
        }
      >
        <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>
          )}

          <div className="space-y-4">
            {/* EN: Full name input field / VI: Trường nhập họ tên */}
            <Controller
              name="fullName"
              control={control}
              render={({ field }) => (
                <Input
                  type="text"
                  variant="solid"
                  label={t('auth.register.fullName')}
                  placeholder="John Doe"
                  isInvalid={!!errors.fullName}
                  errorMessage={errors.fullName?.message}
                  value={field.value}
                  onChange={field.onChange}
                  onBlur={field.onBlur}
                  autoComplete="name"
                  aria-required="true"
                />
              )}
            />

            {/* EN: Email input field / VI: Trường nhập email */}
            <Controller
              name="email"
              control={control}
              render={({ field }) => (
                <Input
                  type="email"
                  variant="solid"
                  label={t('auth.register.email')}
                  placeholder="you@example.com"
                  isInvalid={!!errors.email}
                  errorMessage={errors.email?.message}
                  value={field.value}
                  onChange={field.onChange}
                  onBlur={field.onBlur}
                  autoComplete="email"
                  aria-required="true"
                />
              )}
            />

            {/* EN: Password input field / VI: Trường nhập mật khẩu */}
            <div className="space-y-2">
              <Controller
                name="password"
                control={control}
                render={({ field }) => (
                  <Input
                    type="password"
                    variant="solid"
                    label={t('auth.register.password')}
                    placeholder={t('auth.register.createStrongPassword')}
                    isInvalid={!!errors.password}
                    errorMessage={errors.password?.message}
                    value={field.value}
                    onChange={field.onChange}
                    onBlur={field.onBlur}
                    autoComplete="new-password"
                    aria-required="true"
                  />
                )}
              />

              {/* EN: Password strength indicator / VI: Chỉ báo độ mạnh mật khẩu */}
              {password && (
                <div className="space-y-2 px-1">
                  <div className="flex gap-1.5">
                    {[1, 2, 3, 4].map((step) => (
                      <div
                        key={step}
                        className={cn(
                          'h-1 flex-1 rounded-full transition-all duration-500',
                          passwordStrength.percentage >= step * 25
                            ? getStrengthColor(passwordStrength.strength)
                            : 'bg-bg-tertiary'
                        )}
                      />
                    ))}
                  </div>
                  <p
                    className={cn(
                      'text-[10px] uppercase tracking-wider font-semibold',
                      passwordStrength.strength === 'weak'
                        ? 'text-accent-error'
                        : passwordStrength.strength === 'strong'
                          ? 'text-accent-success'
                          : 'text-accent-warning'
                    )}
                  >
                    {t(`auth.register.${passwordStrength.feedback}`)}
                  </p>
                </div>
              )}
            </div>

            {/* EN: Confirm password input field / VI: Trường xác nhận mật khẩu */}
            <Controller
              name="confirmPassword"
              control={control}
              render={({ field }) => (
                <Input
                  type="password"
                  variant="solid"
                  label={t('auth.register.confirmPassword')}
                  placeholder={t('auth.register.reEnterPassword')}
                  isInvalid={!!errors.confirmPassword}
                  errorMessage={errors.confirmPassword?.message}
                  value={field.value}
                  onChange={field.onChange}
                  onBlur={field.onBlur}
                  autoComplete="new-password"
                  aria-required="true"
                />
              )}
            />

            {/* EN: Terms and conditions checkbox / VI: Checkbox điều khoản và điều kiện */}
            <Controller
              name="terms"
              control={control}
              render={({ field }) => (
                <div className="space-y-2 pt-2">
                  <label className="flex items-start gap-2 cursor-pointer group">
                    <input
                      type="checkbox"
                      checked={field.value}
                      onChange={field.onChange}
                      onBlur={field.onBlur}
                      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 transition-all"
                      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:text-accent-primary-hover font-medium transition-colors"
                        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 animate-in fade-in duration-quick"
                      role="alert"
                    >
                      <span>{errors.terms.message}</span>
                    </p>
                  )}
                </div>
              )}
            />
          </div>

          {/* EN: Submit button with loading state / VI: Nút submit với trạng thái loading */}
          <Button
            type="submit"
            variant="brand"
            size="lg"
            fullWidth
            className="mt-2"
            isLoading={isLoading || isSubmitting}
            isDisabled={isLoading || isSubmitting}
          >
            {isLoading || isSubmitting
              ? t('auth.register.signingUp')
              : t('auth.register.title')}
          </Button>
        </form>
      </AuthCard>
    </>
  );
}
