'use client';

import { useState, useEffect, useMemo } from 'react';
import { useRouter } from '@/i18n/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 { useAuth } from '@/lib/hooks/useAuth';
import { getRememberedEmail } from '@/lib/auth/rememberMe';
import { Button } from '@/components/ui/shared/Button';
import { Checkbox } from '@/components/ui/shared/Checkbox';
import { Input } from '@/components/ui/shared/Input';
import { TopBarControls } from '@/components/ui/shared/TopBarControls';

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

export default function LoginPage() {
  const t = useTranslations('auth');
  const tCommon = useTranslations('common');
  const tValidation = useTranslations('validation');
  const { login, isLoading, user, isAuthReady } = useAuth();
  const router = useRouter();
  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(() => {
    if (isAuthReady && user) {
      router.push('/today');
    }
  }, [user, isAuthReady, router]);

  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) {
      const message = err instanceof Error ? err.message : t('invalidCredentials');
      setError(message || t('invalidCredentials'));
    }
  };

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

  return (
    <div className="relative min-h-screen app-web-bg flex flex-col justify-center py-12 sm:px-6 lg:px-8">
      <div className="absolute top-4 right-4">
        <TopBarControls />
      </div>

      <div className="sm:mx-auto sm:w-full sm:max-w-md">
        <Link href="/" className="flex justify-center">
          <span className="text-3xl font-semibold text-text-primary">{tCommon('appName')}</span>
        </Link>
        <h2 className="mt-6 text-center 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>

      <div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
        <div className="surface-card py-8 px-4 sm:px-10">
          <form className="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 items-center 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-50 border border-red-200 rounded-lg">
                <p className="text-sm text-red-600">{error}</p>
              </div>
            )}

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