import { toNumber } from '~/lib/utils/number';
import Box from '~/src/components/Box';
import ChevronIcon from '~/src/components/Icon/ChevronIcon';
import Loading from '~/src/components/Loading';
import { Select } from '~/src/components/Select2';
import { useApi } from '~/src/hooks/useApi';
import useFetchSessionUser from '~/src/hooks/useFetchSessionUser';
import { useI18n } from '~/src/lib/i18n';
import { getUserArtistsApi } from '~/src/lib/songwhipApi/users/getUserArtistsApi';
import { RoundedTag } from '../../components';
import { SORT_FILTERS, useContentLinksFilters } from '../hooks';

const ALL_ARTISTS_ID = 'all';

export const ContentLinksToolbar = () => {
  const { t } = useI18n('catalog');

  const { userId, userAccountId } = useFetchSessionUser();
  const [filters, setFilters] = useContentLinksFilters();

  const { isLoading, data: artists = [] } = useApi(
    getUserArtistsApi,
    userId && userAccountId ? [userId, userAccountId] : null,
    { enabled: Boolean(userId && userAccountId), keepPreviousData: true }
  );

  const artistOptions = [
    { id: ALL_ARTISTS_ID, text: t('contentLinks.allArtists') },
    ...artists.map(({ id, name }) => ({
      id: String(id),
      text: name,
    })),
  ];

  const selectedArtist = (() => {
    if (filters.artistId) {
      return artistOptions.find(({ id }) => toNumber(id) === filters.artistId);
    }

    return artistOptions[0];
  })();

  return (
    <Box flexBox flexWrap gap="0.8rem">
      <Select
        name="artist"
        testId="contentLinksArtistSelect"
        height="auto"
        value={selectedArtist?.id}
        options={artistOptions}
        isLoading={isLoading}
        onChange={({ value: artistId }) => {
          const id =
            artistId === ALL_ARTISTS_ID ? undefined : toNumber(artistId);

          if (id === filters.artistId) return;
          setFilters({ artistId: id });
        }}
        renderButton={({ isOpened, open, isLoading }) => (
          <RoundedTag
            testId="contentLinksArtistSelectButton"
            isSelected={false}
            isDisabled={isLoading}
            onClick={open}
            text={
              isLoading ? (
                <Box minWidth="10rem" fullHeight centerContent>
                  <Loading size="1.2rem" />
                </Box>
              ) : (
                <Box minWidth="10rem" flexBox fullHeight>
                  <span>{selectedArtist?.text ?? '<unknown>'}</span>
                  <Box margin="0 0 0 auto" centerContent>
                    <ChevronIcon
                      direction={isOpened ? 'up' : 'down'}
                      size="1.8rem"
                      margin="0 0 0 0.5rem"
                    />
                  </Box>
                </Box>
              )
            }
          />
        )}
      />
      <Select
        name="sort"
        testId="contentLinksSortSelect"
        margin="0 0 0 auto"
        value={filters.sort}
        options={SORT_FILTERS.map((sort) => ({
          id: sort,
          text: t(SORTER_TO_I18N_KEY[sort]),
        }))}
        onChange={({ value: sort }) => {
          if (sort === filters.sort) return;
          setFilters({ sort });
        }}
        renderButton={({ isOpened, open }) => (
          <RoundedTag
            testId="contentLinksSortSelectButton"
            isSelected={false}
            onClick={open}
            text={
              <Box flexBox fullHeight>
                <span>{`Sort: ${t(SORTER_TO_I18N_KEY[filters.sort])}`}</span>
                <Box centerContent>
                  <ChevronIcon
                    direction={isOpened ? 'up' : 'down'}
                    size="1.8rem"
                    margin="0 0 0 0.5rem"
                  />
                </Box>
              </Box>
            }
          />
        )}
      />
    </Box>
  );
};

const SORTER_TO_I18N_KEY = {
  updated: 'filters.lastUpdated',
  created: 'filters.lastCreated',
} as const;
