import { useMutation } from '@tanstack/react-query';
import { createFileRoute, useNavigate } from '@tanstack/react-router';
import {
  useEffect,
  useState,
} from 'react';
import z from 'zod';
import { postAuthTokenMutation } from '@/client/@tanstack/react-query.gen';
import { setAccessToken, setRefreshToken } 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();

  const mutation = useMutation({
    ...postAuthTokenMutation(),
    onSuccess: (data) => {
      setAccessToken(data.data!.access_token!);
      setRefreshToken(data.data!.refresh_token!);
      void navigate({ to: '/' });
    },
    onError: () => {
      setStatus('Error getting token');
    },
  });

  useEffect(() => {
    if (mutation.isIdle) {
      mutation.mutate({ body: { code } });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return <div>{status}</div>;
}
