import { useMemo, useState } from 'react';

import Stack from '@material-hu/mui/Stack';

import HuSelectionCard from '@material-hu/components/composed-components/SelectionCard';
import HuInputClassic from '@material-hu/components/design-system/Inputs/Classic';
import HuSkeleton from '@material-hu/components/design-system/Skeleton';
import HuTitle from '@material-hu/components/design-system/Title';

import { useAuth } from 'src/contexts/JWTContext';
import { useGetUserSites } from 'src/hooks/queryHooks/timeTracking';
import { EntryType, UserSite } from 'src/types/timeTracking';
import { useLokaliseTranslation } from 'src/utils/i18n';

type MarkingClockDrawerProps = {
  selectedSite: UserSite | null;
  handleSiteSelection: (site: UserSite) => void;
  entryType: EntryType;
  lastEntrySiteId?: number;
};

const MarkingClockDrawer = ({
  selectedSite,
  handleSiteSelection,
  lastEntrySiteId,
  entryType,
}: MarkingClockDrawerProps) => {
  const [siteSearch, setSiteSearch] = useState('');
  const { t } = useLokaliseTranslation(['time_tracker', 'regions_sites']);
  const { user } = useAuth();

  const { sites, isFetching: isFetchingSites } = useGetUserSites(user?.id!);

  const orderedSites = useMemo(
    () =>
      sites
        ?.filter(site =>
          site.name.toLowerCase().includes(siteSearch.toLowerCase()),
        )
        ?.sort((a, b) => {
          if (a.id === lastEntrySiteId) return -1;
          if (b.id === lastEntrySiteId) return 1;
          return 0;
        }),
    [sites, lastEntrySiteId, siteSearch],
  );

  return (
    <Stack sx={{ gap: 2 }}>
      <HuTitle
        title={t('REGIONS_SITES:CHOOSE_SITE')}
        description={t(
          entryType === EntryType.START
            ? 'SELECT_SITE_BEFORE_CLOCKING_IN'
            : 'SELECT_SITE_BEFORE_CLOCKING_OUT',
        )}
        variant="M"
      />
      <HuInputClassic
        placeholder={t('REGIONS_SITES:SEARCH_SITE')}
        value={siteSearch}
        onChange={setSiteSearch}
        hasCounter={false}
        maxLength={256}
      />
      {isFetchingSites && (
        <>
          <HuSkeleton
            width="100%"
            height={74}
            sx={{ borderRadius: 2 }}
          />
          <HuSkeleton
            width="100%"
            height={74}
            sx={{ borderRadius: 2 }}
          />
        </>
      )}
      {!isFetchingSites &&
        orderedSites?.map(site => (
          <HuSelectionCard
            key={site.id}
            title={site.name}
            checked={site.id === selectedSite?.id}
            onClick={() => {
              handleSiteSelection(site);
            }}
            fullWidth
          >
            <HuTitle
              copetin={
                site.id === lastEntrySiteId ? t('RECENTLY_USED') : undefined
              }
              title={site.name}
              description={site.location?.address}
              variant="S"
              withEllipsis
            />
          </HuSelectionCard>
        ))}
    </Stack>
  );
};

export default MarkingClockDrawer;
