import {
  Badge,
  Button,
  Group,
  Select,
  Stack,
  Tabs,
  Text,
  Title,
  useMantineTheme,
} from '@mantine/core';
import { IconPlayerPause, IconPlayerPlay } from '@tabler/icons';
import { useEffect, useState } from 'react';

import { useElementSize } from '@mantine/hooks';
import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration';
import { useTranslation } from 'next-i18next';
import { UsenetQueueList } from './UsenetQueueList';
import { UsenetHistoryList } from './UsenetHistoryList';
import { BaseTileProps } from '../../components/Dashboard/Tiles/type';
import { ServiceIntegrationType } from '../../types/service';
import { useConfigContext } from '../../config/provider';
import { useGetUsenetInfo, usePauseUsenetQueue, useResumeUsenetQueue } from '../../tools/hooks/api';
import { HomarrCardWrapper } from '../../components/Dashboard/Tiles/HomarrCardWrapper';
import { humanFileSize } from '../../tools/humanFileSize';

dayjs.extend(duration);

const downloadServiceTypes: ServiceIntegrationType['type'][] = ['sabnzbd', 'nzbGet'];

interface UseNetTileProps extends BaseTileProps {}

export const UseNetTile = ({ className }: UseNetTileProps) => {
  const { t } = useTranslation('modules/usenet');
  const { config } = useConfigContext();
  const downloadServices =
    config?.services.filter(
      (x) => x.integration && downloadServiceTypes.includes(x.integration.type)
    ) ?? [];

  const [selectedServiceId, setSelectedService] = useState<string | null>(downloadServices[0]?.id);
  const { data } = useGetUsenetInfo({ serviceId: selectedServiceId! });

  useEffect(() => {
    if (!selectedServiceId && downloadServices.length) {
      setSelectedService(downloadServices[0].id);
    }
  }, [downloadServices, selectedServiceId]);

  const { mutate: pause } = usePauseUsenetQueue({ serviceId: selectedServiceId! });
  const { mutate: resume } = useResumeUsenetQueue({ serviceId: selectedServiceId! });

  if (downloadServices.length === 0) {
    return (
      <HomarrCardWrapper className={className}>
        <Stack>
          <Title order={3}>{t('card.errors.noDownloadClients.title')}</Title>
          <Group>
            <Text>{t('card.errors.noDownloadClients.text')}</Text>
          </Group>
        </Stack>
      </HomarrCardWrapper>
    );
  }

  if (!selectedServiceId) {
    return null;
  }

  const { ref, width, height } = useElementSize();
  const MIN_WIDTH_MOBILE = useMantineTheme().breakpoints.xs;

  return (
    <HomarrCardWrapper className={className}>
      <Tabs keepMounted={false} defaultValue="queue">
        <Tabs.List ref={ref} mb="md" style={{ flex: 1 }} grow>
          <Tabs.Tab value="queue">{t('tabs.queue')}</Tabs.Tab>
          <Tabs.Tab value="history">{t('tabs.history')}</Tabs.Tab>
          {data && (
            <Group position="right" ml="auto">
              {width > MIN_WIDTH_MOBILE && (
                <>
                  <Badge>{humanFileSize(data?.speed)}/s</Badge>
                  <Badge>
                    {t('info.sizeLeft')}: {humanFileSize(data?.sizeLeft)}
                  </Badge>
                </>
              )}
            </Group>
          )}
        </Tabs.List>
        {downloadServices.length > 1 && (
          <Select
            value={selectedServiceId}
            onChange={setSelectedService}
            ml="xs"
            data={downloadServices.map((service) => ({ value: service.id, label: service.name }))}
          />
        )}
        <Tabs.Panel value="queue">
          <UsenetQueueList serviceId={selectedServiceId} />
          {!data ? null : data.paused ? (
            <Button uppercase onClick={() => resume()} radius="xl" size="xs" fullWidth mt="sm">
              <IconPlayerPlay size={12} style={{ marginRight: 5 }} /> {t('info.paused')}
            </Button>
          ) : (
            <Button uppercase onClick={() => pause()} radius="xl" size="xs" fullWidth mt="sm">
              <IconPlayerPause size={12} style={{ marginRight: 5 }} />{' '}
              {dayjs.duration(data.eta, 's').format('HH:mm')}
            </Button>
          )}
        </Tabs.Panel>
        <Tabs.Panel value="history" style={{ display: 'flex', flexDirection: 'column' }}>
          <UsenetHistoryList serviceId={selectedServiceId} />
        </Tabs.Panel>
      </Tabs>
    </HomarrCardWrapper>
  );
};
