'use client';

import { Login } from '@theme/views/login';
import { Register } from '@theme/views/register';
import { useSession } from 'next-auth/react';
import { useSearchParams } from 'next/navigation';
import { useEffect, useMemo, useState } from 'react';
import { useLocalization, useRouter } from '@akinon/next/hooks';
import clsx from 'clsx';
import { twMerge } from 'tailwind-merge';
import { Button } from '@theme/components';
import GuestLogin from '@theme/views/guest-login';

export default function CheckoutAuth() {
  const { data: session } = useSession();
  const router = useRouter();
  const searchParams = useSearchParams();
  const { t } = useLocalization();
  const [activeTab, setActiveTab] = useState('login');

  const tabClass = (tabName) => {
    return twMerge(
      clsx(
        'text-base font-normal text-black-750/50 bg-transparent border-0 border-primary px-6 transition-all hover:border-b hover:text-black-750',
        {
          'border-b text-black-750': activeTab === tabName
        }
      )
    );
  };

  const pageTitle = useMemo(() => {
    return {
      login: t('auth.login.title'),
      register: t('auth.register.title'),
      guest: t('checkout.auth.guest_checkout')
    }[activeTab];
  }, [activeTab]);

  useEffect(() => {
    if (session?.user) {
      router.push(searchParams.get('callbackUrl') ?? '/');
    }
  }, [session?.user]); // eslint-disable-line react-hooks/exhaustive-deps

  return (
    <section className="container my-7 lg:my-24">
      <div className="max-w-lg mx-auto">
        <div className="text-black-750 text-[40px] font-normal">
          {pageTitle}
        </div>
        {activeTab !== 'guest' && (
          <div className="w-full grid grid-cols-2 justify-center gap-4 lg:gap-6 mt-8">
            <button
              className={tabClass('login')}
              onClick={() => setActiveTab('login')}
            >
              {t('auth.login.mobile_title')}
            </button>
            <Button
              className={tabClass('register')}
              onClick={() => setActiveTab('register')}
            >
              {t('auth.register.mobile_title')}
            </Button>
          </div>
        )}
        <div className="w-full flex flex-wrap">
          {activeTab === 'register' && <Register />}

          {activeTab === 'login' && <Login setActiveTab={setActiveTab} />}

          {activeTab === 'guest' && <GuestLogin />}
        </div>
      </div>
    </section>
  );
}
