'use client';

import { Suspense, useState, useEffect, useMemo } from 'react';
import { useSearchParams } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { useTranslations } from 'next-intl';
import { Link } from '@/i18n/navigation';
import { Mail, Lock } from 'lucide-react';
import { getUserFacingError } from '@/components/shared/formatApiError';
import { useAuth } from '@/lib/hooks/useAuth';
import { getRememberedEmail } from '@/lib/auth/rememberMe';
import { AuthPageShell } from '@/components/ui/auth/AuthPageShell';
import { BrandLockup } from '@/components/ui/shared/BrandLockup';
import { Button } from '@/components/ui/shared/Button';
import { Checkbox } from '@/components/ui/shared/Checkbox';
import { Input } from '@/components/ui/shared/Input';
import { storeAuthRedirectFromPath } from '@/lib/auth/postAuthRedirect';
import { useEnterAppWhenAuthenticated } from '@/lib/hooks/useEnterAppWhenAuthenticated';

type LoginForm = {
  email: string;
  password: string;
  rememberMe: boolean;
};

function LoginPageContent() {
  const t = useTranslations('auth');
  const tCommon = useTranslations('common');
  const tValidation = useTranslations('validation');
  const tErrors = useTranslations('errors');
  const { login, isLoading, isAuthReady } = useAuth();
  const searchParams = useSearchParams();
  const [error, setError] = useState<string | null>(null);
  const [savedEmail] = useState(() => getRememberedEmail());

  const loginSchema = useMemo(
    () =>
      z.object({
        email: z.string().email(tValidation('emailInvalid')),
        password: z.string().min(1, tValidation('passwordRequired')),
        rememberMe: z.boolean(),
      }),
    [tValidation],
  );

  useEffect(() => {
    const from = searchParams.get('from');
    if (from) {
      storeAuthRedirectFromPath(from);
    }
  }, [searchParams]);

  useEnterAppWhenAuthenticated();

  const {
    register,
    handleSubmit,
    watch,
    setValue,
    formState: { errors },
  } = useForm<LoginForm>({
    resolver: zodResolver(loginSchema),
    defaultValues: {
      email: savedEmail,
      rememberMe: Boolean(savedEmail),
    },
  });

  const rememberMe = watch('rememberMe');

  const onSubmit = async (data: LoginForm) => {
    try {
      setError(null);
      await login(data.email, data.password, data.rememberMe);
    } catch (err: unknown) {
      setError(getUserFacingError(err, tErrors, t('invalidCredentials')));
    }
  };

  if (!isAuthReady) {
    return (
      <div className="min-h-[100dvh] app-web-bg flex items-center justify-center px-4">
        <p className="text-text-secondary">{tCommon('loading')}</p>
      </div>
    );
  }

  return (
    <AuthPageShell
      header={
        <>
          <Link href="/" className="flex justify-center">
            <BrandLockup className="text-2xl sm:text-3xl text-text-primary" />
          </Link>
          <h2 className="mt-4 sm:mt-6 text-center text-2xl sm:text-3xl font-semibold text-text-primary">
            {t('signInTitle')}
          </h2>
          <p className="mt-2 text-center text-sm text-text-secondary">
            {tCommon('or')}{' '}
            <Link href="/register" className="font-medium text-primary hover:opacity-90">
              {t('startTrialLink')}
            </Link>
          </p>
        </>
      }
    >
      <div className="surface-card py-6 sm:py-8 px-4 sm:px-10">
        <form className="space-y-5 sm:space-y-6" onSubmit={handleSubmit(onSubmit)}>
          <Input
            label={t('email')}
            {...register('email')}
            type="email"
            placeholder={t('emailPlaceholder')}
            error={errors.email?.message}
            icon={<Mail className="h-5 w-5 icon-flat" />}
          />
          <Input
            label={t('password')}
            {...register('password')}
            type="password"
            placeholder={t('passwordPlaceholder')}
            error={errors.password?.message}
            icon={<Lock className="h-5 w-5 icon-flat" />}
            passwordToggleLabels={{
              show: t('showPassword'),
              hide: t('hidePassword'),
            }}
          />

          <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
            <Checkbox
              checked={rememberMe}
              onChange={(checked) => setValue('rememberMe', checked)}
              label={t('rememberMe')}
            />
            <div className="text-sm">
              <Link href="/forgot-password" className="font-medium text-primary hover:opacity-90">
                {t('forgotPassword')}
              </Link>
            </div>
          </div>

          {error && (
            <div className="p-3 bg-red-950/30 border border-red-600/40 rounded-[var(--radius-md)]">
              <p className="text-sm text-red-400">{error}</p>
            </div>
          )}

          <Button type="submit" variant="primary" isLoading={isLoading} fullWidth>
            {t('signIn')}
          </Button>
        </form>
      </div>
    </AuthPageShell>
  );
}

function LoginPageFallback() {
  const tCommon = useTranslations('common');

  return (
    <div className="min-h-[100dvh] app-web-bg flex items-center justify-center px-4">
      <p className="text-text-secondary">{tCommon('loading')}</p>
    </div>
  );
}

export default function LoginPage() {
  return (
    <Suspense fallback={<LoginPageFallback />}>
      <LoginPageContent />
    </Suspense>
  );
}
