'use client';

import { Ban, Clock, Info, KeyRound, Mail } from 'lucide-react';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';

import { AuthCard, AuthLink, SecurityNote } from '@/components/forms/auth-card';
import { describedBy, FormAlert, FormField } from '@/components/forms/form-field';
import { PasswordInput } from '@/components/forms/password-input';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { ApiError } from '@/lib/api-client';
import { useAuth } from '@/lib/auth';
import { site } from '@/lib/marketing';
import { formatWait, safeNextPath } from '@/lib/utils';
import { loginBodySchema, type LoginBody } from '@/shared/schemas/auth';

type LoginAlert =
  | { kind: 'credentials' }
  | { kind: 'locked'; counted: boolean; fallback: string }
  | { kind: 'disabled' }
  | { kind: 'other'; message: string };

const formatClock = (seconds: number): string => `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`;

/** A seconds countdown that ticks once per second after `start` is called. */
function useCountdown(): [number, (seconds: number) => void] {
  const [remaining, setRemaining] = useState(0);
  const running = remaining > 0;
  useEffect(() => {
    if (!running) return undefined;
    const timer = window.setInterval(() => setRemaining((current) => Math.max(0, current - 1)), 1000);
    return () => window.clearInterval(timer);
  }, [running]);
  return [remaining, setRemaining];
}

export function LoginForm() {
  const router = useRouter();
  const params = useSearchParams();
  const { login } = useAuth();
  const [alert, setAlert] = useState<LoginAlert | null>(null);
  const form = useForm<LoginBody>({ resolver: zodResolver(loginBodySchema), mode: 'onBlur' });
  const emailError = form.formState.errors.email?.message;
  const passwordError = form.formState.errors.password?.message;
  const hasNext = safeNextPath(params.get('next')) !== null;
  const [remaining, startCountdown] = useCountdown();

  const onSubmit = form.handleSubmit(async (values) => {
    setAlert(null);
    try {
      const me = await login(values.email, values.password);
      if (me.tenant.status === 'SUSPENDED') {
        router.push('/suspended');
        return;
      }
      if (me.user.isSuperAdmin) {
        router.push('/admin');
        return;
      }
      router.push(safeNextPath(params.get('next')) ?? '/dashboard');
    } catch (error) {
      if (error instanceof ApiError && error.code === 'INVALID_CREDENTIALS') {
        setAlert({ kind: 'credentials' });
        return;
      }
      if (error instanceof ApiError && error.code === 'TOO_MANY_ATTEMPTS') {
        const seconds = error.retryAfterSeconds;
        startCountdown(seconds ?? 0);
        setAlert({ kind: 'locked', counted: seconds !== undefined, fallback: seconds === undefined ? 'a few minutes' : formatWait(seconds) });
        return;
      }
      if (error instanceof ApiError && error.code === 'ACCOUNT_DISABLED') {
        setAlert({ kind: 'disabled' });
        return;
      }
      setAlert({ kind: 'other', message: error instanceof ApiError ? error.message : 'Something went wrong. Try again.' });
    }
  });

  return (
    <AuthCard
      title="Welcome back"
      description="Sign in to manage your shipments."
      top={
        hasNext ? (
          <span className="inline-flex items-center gap-1.5 rounded-pill bg-info-soft px-3 py-1 text-caption font-semibold text-info">
            <Info className="h-3.5 w-3.5" aria-hidden="true" />
            Sign in to continue
          </span>
        ) : undefined
      }
      footer={
        <>
          New to {site.name}? <AuthLink href="/register">Create an account</AuthLink>
        </>
      }
    >
      <form className="grid gap-5" onSubmit={onSubmit} noValidate>
        {alert?.kind === 'credentials' ? (
          <FormAlert icon={<KeyRound />} title="Email or password is incorrect.">
            Check the details and try again.
          </FormAlert>
        ) : null}
        {alert?.kind === 'locked' ? (
          <FormAlert tone="warning" icon={<Clock />} title="Too many attempts.">
            {alert.counted && remaining > 0 ? (
              <>
                Try again in <span className="font-semibold tabular-nums text-foreground">{formatClock(remaining)}</span>.
              </>
            ) : alert.counted ? (
              'You can try again now.'
            ) : (
              `Try again in ${alert.fallback}.`
            )}
          </FormAlert>
        ) : null}
        {alert?.kind === 'disabled' ? (
          <FormAlert icon={<Ban />} title="This account is disabled.">
            Contact <a className="font-medium text-primary underline-offset-4 hover:underline" href={`mailto:${site.supportEmail}`}>{site.supportEmail}</a>.
          </FormAlert>
        ) : null}
        {alert?.kind === 'other' ? <FormAlert>{alert.message}</FormAlert> : null}

        <FormField id="email" label="Email" error={emailError}>
          <Input
            id="email"
            type="email"
            autoComplete="email"
            placeholder="you@company.com"
            leading={<Mail />}
            aria-invalid={emailError !== undefined}
            aria-describedby={describedBy('email', undefined, emailError)}
            {...form.register('email')}
          />
        </FormField>
        <FormField
          id="password"
          label="Password"
          error={passwordError}
          labelAction={
            <Link href="/forgot-password" className="rounded-sm text-small font-semibold text-primary underline-offset-4 hover:underline">
              Forgot password?
            </Link>
          }
        >
          <PasswordInput id="password" autoComplete="current-password" aria-invalid={passwordError !== undefined} aria-describedby={describedBy('password', undefined, passwordError)} {...form.register('password')} />
        </FormField>
        <Button type="submit" size="lg" className="mt-1 w-full" loading={form.formState.isSubmitting}>
          {form.formState.isSubmitting ? 'Signing in' : 'Sign in'}
        </Button>
        <SecurityNote />
      </form>
    </AuthCard>
  );
}
