'use client';

import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { useRouter, useSearchParams } from 'next/navigation';
import Link from 'next/link';
import { toast } from 'sonner';
import { loginSchema, type LoginInput } from '@/lib/validations/auth';
import { createClient } from '@/lib/supabase/client';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';

export default function LoginPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const next = searchParams.get('next') ?? '/dashboard';
  const [submitting, setSubmitting] = useState(false);
  const [googleLoading, setGoogleLoading] = useState(false);

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<LoginInput>({ resolver: zodResolver(loginSchema) });

  async function onSubmit(values: LoginInput) {
    setSubmitting(true);
    const supabase = createClient();
    const { data, error } = await supabase.auth.signInWithPassword(values);

    if (error) {
      toast.error(error.message);
      setSubmitting(false);
      return;
    }

    // If the user has 2FA enabled, route them through the OTP challenge
    // before landing on the dashboard, instead of granting access immediately.
    const { data: profile } = await supabase
      .from('profiles')
      .select('two_factor_enabled')
      .eq('id', data.user.id)
      .single();

    if (profile?.two_factor_enabled) {
      router.push(`/verify-otp?email=${encodeURIComponent(values.email)}&next=${encodeURIComponent(next)}`);
    } else {
      router.push(next);
    }
    setSubmitting(false);
  }

  async function onGoogleLogin() {
    setGoogleLoading(true);
    const supabase = createClient();
    const { error } = await supabase.auth.signInWithOAuth({
      provider: 'google',
      options: { redirectTo: `${window.location.origin}/auth/callback?next=${encodeURIComponent(next)}` },
    });
    if (error) {
      toast.error(error.message);
      setGoogleLoading(false);
    }
  }

  return (
    <div>
      <h1 className="font-display text-2xl text-ink dark:text-paper">Welcome back</h1>
      <p className="mt-1 text-sm text-ink-muted dark:text-slate-muted">Log in to manage your wallet.</p>

      <Button variant="ghost" isLoading={googleLoading} onClick={onGoogleLogin} className="w-full mt-6">
        Continue with Google
      </Button>

      <div className="my-6 flex items-center gap-3">
        <div className="h-px flex-1 bg-black/10 dark:bg-white/10" />
        <span className="text-xs text-ink-muted dark:text-slate-muted">or</span>
        <div className="h-px flex-1 bg-black/10 dark:bg-white/10" />
      </div>

      <form onSubmit={handleSubmit(onSubmit)} className="space-y-4" noValidate>
        <Input label="Email" type="email" {...register('email')} error={errors.email?.message} />
        <Input label="Password" type="password" {...register('password')} error={errors.password?.message} />

        <div className="flex justify-end">
          <Link href="/forgot-password" className="text-xs text-azure font-medium">
            Forgot password?
          </Link>
        </div>

        <Button type="submit" isLoading={submitting} className="w-full">
          Log in
        </Button>
      </form>

      <p className="mt-6 text-sm text-ink-muted dark:text-slate-muted">
        New to SwiftPay?{' '}
        <Link href="/register" className="text-azure font-medium">
          Create an account
        </Link>
      </p>
    </div>
  );
}
