import { createFileRoute, Navigate } from '@tanstack/react-router';
import { zodValidator } from '@tanstack/zod-adapter';
import z from 'zod';
import { LoginForm } from '@/components/login-form';
import { useValidateMagicLink } from '@/hooks/data/useValidateMagicLink';
import { setRefreshToken, setToken } from '@/lib/token';

const loginMagicLinkReceiverSchema = z.object({
  ticket: z.string().optional(),
});

export const Route = createFileRoute('/login')({
  component: RouteComponent,
  validateSearch: zodValidator(loginMagicLinkReceiverSchema),
});

function ReceiveMagicLinkComponent() {
  const { ticket } = Route.useSearch();
  const { data } = useValidateMagicLink(ticket!);

  setToken(data.data.access_token);
  setRefreshToken(data.data.refresh_token);

  return <Navigate to="/" />;
}

function RouteComponent() {
  const { ticket } = Route.useSearch();
  return (
    <div className="bg-background flex min-h-svh flex-col items-center justify-center gap-6 p-6 md:p-10">
      <div className="w-full max-w-sm">
        {ticket === undefined ? <LoginForm /> : <ReceiveMagicLinkComponent />}
      </div>
    </div>
  );
}
