import { useEffect } from 'react';

import type { FC } from 'react';

import { PageTypes } from '~/lib/types';
import ErrorText from '~/src/components/ErrorText';
import Loading from '~/src/components/Loading';
import { useAppLoading } from '~/src/components/NextApp/lib/CoreUi';
import Text from '~/src/components/Text';
import useIsEnabled from '~/src/hooks/useIsEnabled';
import { useI18n } from '~/src/lib/i18n';
import { TrackerProvider } from '~/src/lib/tracker/useTracker';
import { Features } from '~/src/store/session/types';
import { AccountListCard, AccountSection } from '..';
import useAccount from '../../useAccount';
import {
  ChannelsSection,
  CustomBrandsList,
  CustomDomainsSection,
  FacebookPixelSection,
  GoogleTagManagerSection,
} from './components';

const AccountDetails: FC = () => {
  const { t } = useI18n('account');
  const { account, accountIsLoading, accountError, setAccount } = useAccount();

  const isSetupCustomDomainEnabled = useIsEnabled(Features.SETUP_CUSTOM_DOMAIN);
  const isGoogleTagManagerEnabled = useIsEnabled(Features.GOOGLE_TAG_MANAGER);
  const isChannelsEnabled = useIsEnabled(Features.CONTENT_LINKS);

  /* 
    We will bring this functionality back one day after launch
    https://theorchard.atlassian.net/browse/AD-991
  */
  // const renderContactSupport = ({
  //   withLineBreak,
  // }: {
  //   withLineBreak: boolean;
  // }) =>
  //   tx('customDomains.contactSupport', {
  //     br: withLineBreak ? <br /> : <></>,
  //     contact:
  //       account.orchardBrand === OrchardBrands.SME ? (
  //         <Link
  //           href="mailto:product-support@sonymusic-pde.com"
  //           isUnderlined
  //           withHoverStyle
  //         >
  //           Product Support
  //         </Link>
  //       ) : (
  //         'Account Manager'
  //       ),
  //   });

  const setIsAppLoading = useAppLoading();

  useEffect(() => {
    // show the app global loading bar when account in 'loading' state
    setIsAppLoading(accountIsLoading);
  }, [accountIsLoading, setIsAppLoading]);

  if (accountIsLoading) return <Loading margin="4rem" />;

  if (accountError) {
    return (
      <AccountSection>
        <ErrorText error={accountError} centered />
      </AccountSection>
    );
  }

  // edge case when we don't have an account
  if (!account) {
    return <Text centered>{t('error', { icon: '🤨' })}</Text>;
  }

  return (
    <TrackerProvider
      baseContext={{
        // Add the `account` id and name to trackerParams so it's included with
        // all events dispatched lower down the react tree.
        accountId: account?.id,
        accountName: account?.name,

        pageType: PageTypes.ACCOUNT,
      }}
    >
      <div>
        <CustomBrandsList account={account} onAccountChange={setAccount} />
        {account.users && (
          <AccountSection
            testId="teamMembers"
            title={t('teamSectionTitle')}
            description={t('orchardTeamSectionDescription')}
          >
            <AccountListCard
              items={account.users.map(({ image, id, name, email }) => ({
                title: name || email,
                subtitle: name && email,
                image,
                key: String(id),
                testId: 'teamMemberItem',
              }))}
            />
          </AccountSection>
        )}
        {isGoogleTagManagerEnabled && (
          <GoogleTagManagerSection
            account={account}
            onAccountChange={setAccount}
          />
        )}
        <FacebookPixelSection account={account} onAccountChange={setAccount} />
        {isChannelsEnabled && <ChannelsSection account={account} />}
        {isSetupCustomDomainEnabled && (
          <CustomDomainsSection
            account={account}
            onAccountChange={setAccount}
            /*
                    We will bring this functionality back one day after launch
                    https://theorchard.atlassian.net/browse/AD-991
                  */
            // isEditable={isSetupCustomDomainEnabled}
            // emptyHint={
            //   isSetupCustomDomainEnabled
            //     ? undefined
            //     : renderContactSupport({ withLineBreak: true })
            // }
            // renderAdditionalDescription={(itemsCount) => {
            //   const contactSupportMessage =
            //     itemsCount > 0
            //       ? renderContactSupport({ withLineBreak: false })
            //       : undefined;

            //   return isSetupCustomDomainEnabled ? undefined : contactSupportMessage;
            // }}
          />
        )}
      </div>
    </TrackerProvider>
  );
};

export default AccountDetails;
