import { createFileRoute } from '@tanstack/react-router';
import { zodValidator } from '@tanstack/zod-adapter';
import { isNil } from 'lodash-es';
import z from 'zod';
import { LoginForm } from '@/components/login-form';
import { axiosClient } from '@/lib/axios';
import { generateOAuthState } from '@/lib/random';
import { getToken } from '@/lib/token';

const authorizeSchema = z.object({
  response_type: z.literal('code').default('code'),
  client_id: z.literal('org_client').default('org_client'),
  redirect_uri: z.string().default(`${new URL(import.meta.env.VITE_APP_BASE_URL as string).toString()}token`),
  state: z.string().default(generateOAuthState()),
});

export type AuthorizeSearchParams = z.infer<typeof authorizeSchema>;

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

function RouteComponent() {
  const token = getToken();
  const oauthParams = Route.useSearch();
  /**
   * Auth by Token Flow
   */
  if (!isNil(token)) {
    axiosClient.post<{ redirect_uri: string }>('/auth/exchange', {
      client_id: oauthParams.client_id,
      redirect_uri: oauthParams.redirect_uri,
      state: oauthParams.state,
    }).then((res) => {
      window.location.href = res.data.redirect_uri;
    }).catch((e) => {
      console.error(e);
      return 'Token exchange failed';
    });
    return 'Redirecting';
  }
  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">
        <LoginForm oauthParams={oauthParams} />
      </div>
    </div>
  );
}
