'use client';

import { useRouter } from 'next/navigation';

import type { Provider } from '@supabase/supabase-js';

import { useSupabase } from '@/packages/supabase/src/hooks/use-supabase';

import { isBrowser } from '@kit/shared/utils';
import { If } from '@kit/ui/if';
import { Separator } from '@kit/ui/separator';
import { Trans } from '@kit/ui/trans';

import { MagicLinkAuthContainer } from './magic-link-auth-container';
import { OauthProviders } from './oauth-providers';
import { PasswordSignInContainer } from './password-sign-in-container';

export type Providers = {
  password: boolean;
  magicLink: boolean;
  oAuth: Provider[];
};

export function SignInMethodsContainer(props: {
  inviteToken?: string;

  paths: {
    callback: string;
    joinTeam: string;
    returnPath: string;
    updateAccount: string;
  };

  providers: Providers;
}) {
  const client = useSupabase();
  const router = useRouter();

  const redirectUrl = isBrowser()
    ? new URL(props.paths.callback, window?.location.origin).toString()
    : '';

  const onSignIn = async (userId?: string) => {
    // if the user has an invite token, we should join the team
    if (props.inviteToken) {
      const searchParams = new URLSearchParams({
        invite_token: props.inviteToken,
      });

      const joinTeamPath = props.paths.joinTeam + '?' + searchParams.toString();

      router.replace(joinTeamPath);
    } else {
      if (!userId) {
        router.replace(props.paths.callback);
        return;
      }

      try {
        const { data: hasConsentPersonalData } = await client
          .schema('medreport')
          .rpc('has_consent_personal_data', {
            account_id: userId,
          });

        if (hasConsentPersonalData) {
          router.replace(props.paths.returnPath);
        } else {
          router.replace(props.paths.updateAccount);
        }
      } catch {
        router.replace(props.paths.callback);
        return;
      }
    }
  };

  return (
    <>
      <If condition={props.providers.password}>
        <PasswordSignInContainer onSignIn={onSignIn} />
      </If>

      <If condition={props.providers.magicLink}>
        <MagicLinkAuthContainer
          inviteToken={props.inviteToken}
          redirectUrl={redirectUrl}
          shouldCreateUser={false}
        />
      </If>

      <If condition={props.providers.oAuth.length}>
        <div className="relative">
          <div className="absolute inset-0 flex items-center">
            <Separator />
          </div>

          <div className="relative flex justify-center text-xs uppercase">
            <span className="bg-background text-muted-foreground px-2">
              <Trans i18nKey="auth:orContinueWith" />
            </span>
          </div>
        </div>

        <OauthProviders
          enabledProviders={props.providers.oAuth}
          inviteToken={props.inviteToken}
          shouldCreateUser={false}
          paths={{
            callback: props.paths.callback,
            returnPath: props.paths.returnPath,
          }}
          queryParams={{
            prompt: 'login',
          }}
        />
      </If>
    </>
  );
}
