import { useMemo } from 'react';

import type { MappedAccount } from '~/lib/songwhipApi/types';
import type { SelectButtonProps } from '~/src/components/Select2/types';
import type { FC } from 'react';

import Card from '~/src/components/Card';
import Clickable from '~/src/components/Clickable';
import ErrorText from '~/src/components/ErrorText';
import ChevronIcon from '~/src/components/Icon/ChevronIcon';
import ListItem from '~/src/components/ListItem';
import Loading from '~/src/components/Loading';
import { Select } from '~/src/components/Select2';
import { useI18n } from '~/src/lib/i18n';
import { AccountSection } from '..';
import useAccount from '../../useAccount';
import AccountDetails from '../AccountDetails';

interface AccountsProps {
  accounts: MappedAccount[];
  updateAccountId(accountId: number): void;
}

export const Accounts: FC<AccountsProps> = ({ accounts, updateAccountId }) => {
  const { account, accountIsLoading, accountError } = useAccount();

  const { t } = useI18n('account');

  const accountOptions = useMemo(
    () =>
      accounts
        .filter(
          (account): account is Omit<MappedAccount, 'key'> & { key: string } =>
            Boolean(account.key)
        )
        .map(({ key, name }) => ({
          id: key,
          text: name,
        })),
    [accounts]
  );

  if (!account && !accountError) {
    return <Loading margin="4rem" />;
  }

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

  if (accounts.length === 1) {
    return <AccountDetails />;
  }

  // user has multiple accounts
  return (
    <>
      <AccountSection title={t('selectedAccount')}>
        <Select
          testId="accountSelect"
          width="100%"
          value={account?.key}
          options={accountOptions}
          onChange={({ value: key, prevValue }) => {
            if (!key || key === prevValue) return;

            const nextAccount = accounts.find((account) => account.key === key);

            if (nextAccount) {
              updateAccountId(nextAccount.id);
            }
          }}
          searchFeature={{
            type: 'search',
            placeholder: t('selectAccountSearchPlaceholder'),
          }}
          renderButton={({ option, open, isOpened }: SelectButtonProps) => (
            <Card>
              <Clickable
                testId="accountSelectButton"
                onClick={open}
                isDisabled={accountIsLoading}
              >
                <ListItem
                  padding="1.6rem 2rem"
                  // no need to i18n, edge case
                  title={option?.text ?? 'No account selected'}
                  subtitle={option?.caption}
                  renderAfter={() => (
                    <ChevronIcon
                      size="1.7rem"
                      margin="0 0 0 1rem"
                      direction={isOpened ? 'up' : 'down'}
                    />
                  )}
                />
              </Clickable>
            </Card>
          )}
        />
      </AccountSection>
      <AccountDetails />
    </>
  );
};
