'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 } 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 { useTranslations } from 'next-intl';
import { AuthControls } from '@/features/shared/components/layout/auth-controls';
import { AuthCard } from '@/features/auth/components/auth-card';

/**
 * EN: Create login schema with translated messages
 * VI: Tạo login schema với thông báo đã dịch
 */
function createLoginSchema(t: (key: string) => string) {
  return z.object({
    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')),
    rememberMe: z.boolean().optional(),
  });
}

/**
 * EN: LoginFormData type - will be inferred from schema in component
 * VI: Kiểu LoginFormData - sẽ được suy luận từ schema trong component
 */

/**
 * EN: Login page component for user authentication
 * VI: Component trang đăng nhập để xác thực người dùng
 *
 * Features:
 * - Email/password inputs with validation
 * - Real-time error messages
 * - Remember me checkbox
 * - Forgot password link
 * - Loading state on button
 * - Error handling
 */
export default function LoginPage() {
  // 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 login functionality
  // VI: Auth store hooks cho chức năng đăng nhập
  const { login, 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 loginSchema = createLoginSchema(t);
  type LoginFormData = z.infer<typeof loginSchema>;

  // EN: React Hook Form setup with Zod resolver
  // VI: Setup React Hook Form với Zod resolver
  const {
    control,
    handleSubmit,
    formState: { errors, isSubmitting },
  } = useForm<LoginFormData>({
    resolver: zodResolver(loginSchema),
    defaultValues: {
      email: '',
      password: '',
      rememberMe: false,
    },
  });

  /**
   * EN: Handle form submission for login
   * VI: Xử lý submit form để đăng nhập
   *
   * @param data - Form data validated by Zod / Dữ liệu form đã được validate bởi Zod
   */
  const onSubmit = async (data: LoginFormData) => {
    setApiError('');
    try {
      // EN: Attempt login through auth store
      // VI: Thử đăng nhập thông qua auth store
      await login(data.email, data.password);
      // EN: Redirect to dashboard on successful login
      // VI: Chuyển hướng về dashboard khi đăng nhập 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.login.loginFailed'));
    }
  };

  return (
    <>
      <AuthControls />
      <AuthCard
        title={t('auth.login.title')}
        description={t('auth.login.description')}
        footer={
          <span>
            {t('auth.login.noAccount')}{' '}
            <Link
              href="/register"
              className="text-accent-primary hover:text-accent-primary-hover font-medium transition-colors"
            >
              {t('auth.login.signUp')}
            </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: Email input field / VI: Trường nhập email */}
            <Controller
              name="email"
              control={control}
              render={({ field }) => (
                <Input
                  type="email"
                  variant="solid"
                  label={t('auth.login.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-1">
              <Controller
                name="password"
                control={control}
                render={({ field }) => (
                  <Input
                    type="password"
                    variant="solid"
                    label={t('auth.login.password')}
                    placeholder={t('auth.login.password')}
                    isInvalid={!!errors.password}
                    errorMessage={errors.password?.message}
                    value={field.value}
                    onChange={field.onChange}
                    onBlur={field.onBlur}
                    autoComplete="current-password"
                    aria-required="true"
                  />
                )}
              />

              <div className="flex items-center justify-between pt-2">
                <label className="flex items-center gap-2 cursor-pointer group">
                  <Controller
                    name="rememberMe"
                    control={control}
                    render={({ field }) => (
                      <input
                        type="checkbox"
                        checked={field.value}
                        onChange={field.onChange}
                        onBlur={field.onBlur}
                        className="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 transition-all"
                      />
                    )}
                  />
                  <span className="text-sm text-text-secondary group-hover:text-text-primary transition-colors">
                    {t('auth.login.rememberMe')}
                  </span>
                </label>

                <Link
                  href="/forgot-password"
                  className="text-sm font-medium text-accent-primary hover:text-accent-primary-hover transition-colors"
                >
                  {t('auth.login.forgotPassword')}
                </Link>
              </div>
            </div>
          </div>

          <Button
            type="submit"
            variant="brand"
            size="lg"
            className="w-full mt-4"
            isLoading={isLoading || isSubmitting}
            isDisabled={isLoading || isSubmitting}
          >
            {isLoading || isSubmitting
              ? t('auth.login.signingIn')
              : t('auth.login.title')}
          </Button>
        </form>
      </AuthCard>
    </>
  );
}
