'use client';

import Link from 'next/link';
import { Suspense, type FormEvent, useCallback, useMemo, useState } from 'react';
import { useSearchParams } from 'next/navigation';
import { AuthShell } from '@/components/auth/auth-shell';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { useAuthHandoff } from '@/hooks/use-auth-handoff';
import { authClient } from '@/lib/auth-client';

function sanitizeNextPath(value: string | null) {
  if (!value || !value.startsWith('/')) {
    return '/';
  }

  return value;
}

export default function SignInPage() {
  return (
    <Suspense fallback={<div className="flex min-h-screen items-center justify-center text-sm text-[color:var(--terminal-muted)]">Loading sign in...</div>}>
      <SignInPageContent />
    </Suspense>
  );
}

function SignInPageContent() {
  const searchParams = useSearchParams();
  const nextPath = useMemo(() => sanitizeNextPath(searchParams.get('next')), [searchParams]);
  const { data: rawSession, isPending } = authClient.useSession();
  const session = (rawSession ?? null) as { user?: { id?: string } } | null;

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [handoffError, setHandoffError] = useState<string | null>(null);
  const [message, setMessage] = useState<string | null>(null);
  const [busyAction, setBusyAction] = useState<'password' | 'magic' | null>(null);
  const [awaitingSession, setAwaitingSession] = useState(false);

  const handleHandoffTimeout = useCallback(() => {
    setAwaitingSession(false);
    setHandoffError('Authentication completed, but the session was not established on this device. Please sign in again.');
  }, []);

  const { isHandingOff, statusText } = useAuthHandoff({
    nextPath,
    session,
    isPending,
    awaitingSession,
    onTimeout: handleHandoffTimeout
  });

  const signInWithPassword = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setError(null);
    setHandoffError(null);
    setMessage(null);
    setBusyAction('password');

    const { error: signInError } = await authClient.signIn.email({
      email: email.trim(),
      password,
      callbackURL: nextPath
    });

    setBusyAction(null);

    if (signInError) {
      setError(signInError.message || 'Sign in failed.');
      return;
    }

    setAwaitingSession(true);
  };

  const signInWithMagicLink = async () => {
    const targetEmail = email.trim();
    if (!targetEmail) {
      setError('Email is required for magic link sign in.');
      return;
    }

    setError(null);
    setHandoffError(null);
    setMessage(null);
    setBusyAction('magic');

    const { error: magicError } = await authClient.signIn.magicLink({
      email: targetEmail,
      callbackURL: nextPath
    });

    setBusyAction(null);

    if (magicError) {
      setError(magicError.message || 'Unable to send magic link.');
      return;
    }

    setMessage('Magic link sent. Check your inbox and open the link on this device.');
  };

  return (
    <AuthShell
      title="Secure Sign In"
      subtitle="Use email/password or request a magic link."
      footer={(
        <>
          Need an account?{' '}
          <Link href={`/auth/signup${nextPath !== '/' ? `?next=${encodeURIComponent(nextPath)}` : ''}`} className="text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]">
            Create one
          </Link>
        </>
      )}
    >
      <form className="space-y-4" onSubmit={signInWithPassword}>
        <div>
          <label className="mb-1 block text-xs uppercase tracking-[0.2em] text-[color:var(--terminal-muted)]">Email</label>
          <Input
            type="email"
            autoComplete="email"
            value={email}
            onChange={(event) => setEmail(event.target.value)}
            required
            disabled={busyAction !== null || isHandingOff}
          />
        </div>

        <div>
          <label className="mb-1 block text-xs uppercase tracking-[0.2em] text-[color:var(--terminal-muted)]">Password</label>
          <Input
            type="password"
            autoComplete="current-password"
            value={password}
            onChange={(event) => setPassword(event.target.value)}
            required
            disabled={busyAction !== null || isHandingOff}
          />
        </div>

        {error ? <p className="text-sm text-[#ff9f9f]">{error}</p> : null}
        {handoffError ? <p className="text-sm text-[#ff9f9f]">{handoffError}</p> : null}
        {message ? <p className="text-sm text-[color:var(--accent)]">{message}</p> : null}
        {statusText ? <p className="text-sm text-[color:var(--terminal-muted)]">{statusText}</p> : null}

        <Button type="submit" className="w-full" disabled={busyAction !== null || isHandingOff}>
          {busyAction === 'password'
            ? 'Signing in...'
            : isHandingOff
              ? 'Finishing sign-in...'
              : 'Sign in with password'}
        </Button>
      </form>

      <div className="mt-4">
        <Button
          type="button"
          variant="secondary"
          className="w-full"
          disabled={busyAction !== null || isHandingOff}
          onClick={() => void signInWithMagicLink()}
        >
          {busyAction === 'magic'
            ? 'Sending link...'
            : isHandingOff
              ? 'Finishing sign-in...'
              : 'Send magic link'}
        </Button>
      </div>
    </AuthShell>
  );
}
