import { createFileRoute, useNavigate } from '@tanstack/react-router';
import { useState } from 'react';
import z from 'zod';
import { doSetTokenByCode } from '@/lib/token';

const tokenCodeSchema = z.object({
  code: z.string().nonempty(),
});

export const Route = createFileRoute('/token')({
  component: RouteComponent,
  validateSearch: tokenCodeSchema,
});

function RouteComponent() {
  const { code } = Route.useSearch();
  const [status, setStatus] = useState('Loading...');
  const navigate = useNavigate();
  doSetTokenByCode(code).then(() => {
    void navigate({ to: '/' });
  }).catch((_) => {
    setStatus('Error getting token');
  });
  return <div>{status}</div>;
}
