'use client';

import dynamic from 'next/dynamic';
import Link from 'next/link';

import { UserWorkspace } from '@/app/home/(user)/_lib/server/load-user-workspace';
import { useQuery } from '@tanstack/react-query';

import { PersonalAccountDropdown } from '@kit/accounts/personal-account-dropdown';
import { featureFlagsConfig, pathsConfig } from '@kit/shared/config';
import { useAuthConfig } from '@kit/shared/hooks';
import { useSignOut } from '@kit/supabase/hooks/use-sign-out';
import { useSupabase } from '@kit/supabase/hooks/use-supabase';
import { Button } from '@kit/ui/button';
import { If } from '@kit/ui/if';
import { Trans } from '@kit/ui/trans';

const ModeToggle = dynamic(() =>
  import('@kit/ui/mode-toggle').then((mod) => ({
    default: mod.ModeToggle,
  })),
);

const paths = {
  home: pathsConfig.app.home,
  admin: pathsConfig.app.admin,
  doctor: pathsConfig.app.doctor,
  personalAccountSettings: pathsConfig.app.personalAccountSettings,
};

const features = {
  enableThemeToggle: featureFlagsConfig.enableThemeToggle,
};

export function SiteHeaderAccountSection({
  accounts,
}: {
  accounts: UserWorkspace['accounts'];
}) {
  const session = useSession();
  const signOut = useSignOut();

  if (session.data) {
    return (
      <PersonalAccountDropdown
        showProfileName={false}
        paths={paths}
        features={features}
        user={session.data.user}
        signOutRequested={() => signOut.mutateAsync()}
        accounts={accounts}
      />
    );
  }

  return <AuthButtons />;
}

function AuthButtons() {
  const { config } = useAuthConfig();

  return (
    <div className={'animate-in fade-in flex gap-x-2.5 duration-500'}>
      <div className={'hidden md:flex'}>
        <If condition={features.enableThemeToggle}>
          <ModeToggle />
        </If>
      </div>

      {config && (
        <div className={'flex gap-x-2.5'}>
          {(config.providers.password || config.providers.oAuth.length > 0) && (
            <Button className={'block'} asChild variant={'ghost'}>
              <Link href={pathsConfig.auth.signIn}>
                <Trans i18nKey={'auth:signIn'} />
              </Link>
            </Button>
          )}

          {config.providers.password && (
            <Button asChild className="text-xs md:text-sm" variant={'default'}>
              <Link href={pathsConfig.auth.signUp}>
                <Trans i18nKey={'auth:signUp'} />
              </Link>
            </Button>
          )}
        </div>
      )}
    </div>
  );
}

function useSession() {
  const client = useSupabase();

  return useQuery({
    queryKey: ['session'],
    queryFn: async () => {
      const { data } = await client.auth.getSession();

      return data.session;
    },
  });
}
