import Box from '~/src/components/Box';
import ChevronIcon from '~/src/components/Icon/ChevronIcon';
import { Select } from '~/src/components/Select2';
import useIsLargeScreen from '~/src/hooks/useIsLargeScreen';
import { useI18n } from '~/src/lib/i18n';
import { RoundedTag } from '../../components';
import {
  CATALOG_TYPE_FILTERS,
  getCatalogTypeFilter,
} from '../catalogTypeFilters';
import { useCatalogFilters } from '../hooks';
import { SORT_FILTERS } from '../hooks/useCatalogFilters';
import { FilterChips } from './FilterChips';

export const PagesToolbar = ({
  showArchivedFilter,
}: {
  showArchivedFilter?: boolean;
}) => {
  const { t } = useI18n('catalog');
  const { t: appT } = useI18n('app');
  const isLargeScreen = useIsLargeScreen();
  const [filters, setFilters] = useCatalogFilters();

  const availableTypeFilters = CATALOG_TYPE_FILTERS.filter((filter) => {
    // Do not show archived filter unless it is already selected
    if (
      filter.id === 'archived' &&
      !showArchivedFilter &&
      filters.type !== 'archived'
    ) {
      return false;
    }

    return true;
  });

  const selectedTypeFilter = getCatalogTypeFilter(filters.type);

  return (
    <Box flexBox alignStart gap="0.8rem">
      {isLargeScreen ? (
        // Desktop: chips on a single row, collapsing behind a "+N" pill.
        <FilterChips
          items={availableTypeFilters.map((filter) => ({
            id: filter.id,
            text: appT(filter.labelKey),
          }))}
          selectedId={filters.type}
          onSelect={(type) => setFilters({ type })}
        />
      ) : (
        // Mobile: a dropdown reads better than horizontally-collapsed chips on
        // narrow screens.
        <Box noFlexShrink style={{ marginRight: 'auto' }}>
          <Select
            name="filter"
            testId="catalogTypeSelect"
            value={filters.type}
            options={availableTypeFilters.map((filter) => ({
              id: filter.id,
              text: appT(filter.labelKey),
            }))}
            onChange={({ value: type }) => {
              if (type === filters.type) return;
              setFilters({ type });
            }}
            renderButton={({ isOpened, open }) => (
              <RoundedTag
                testId="catalogTypeSelectButton"
                isSelected={false}
                onClick={open}
                text={
                  <Box flexBox fullHeight>
                    <span>
                      {t('filterType', {
                        type: appT(
                          selectedTypeFilter?.labelKey ?? 'labels.all'
                        ),
                      })}
                    </span>
                    <Box centerContent>
                      <ChevronIcon
                        direction={isOpened ? 'up' : 'down'}
                        size="1.8rem"
                        margin="0 0 0 0.5rem"
                      />
                    </Box>
                  </Box>
                }
              />
            )}
          />
        </Box>
      )}
      <Box noFlexShrink>
        <Select
          name="sort"
          testId="catalogSortSelect"
          value={filters.sort}
          options={SORT_FILTERS.map((sorter) => ({
            id: sorter,
            text: t(SORTER_TO_I18N_KEY[sorter]),
          }))}
          onChange={({ value: sort }) => {
            if (sort === filters.sort) return;
            setFilters({ sort });
          }}
          renderButton={({ isOpened, open }) => (
            <RoundedTag
              testId="catalogSortSelectButton"
              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>
    </Box>
  );
};

const SORTER_TO_I18N_KEY = {
  updated: 'filters.lastUpdated',
  released: 'filters.latestReleaseDate',
} as const;
