import type { MappedContentLink } from '~/lib/songwhipApi/mapper';
import type { SongwhipChannel } from '~/lib/songwhipApi/types';
import type { DataTableColumn } from '~/src/components/Table';

import { SongwhipChannelMediums } from '~/lib/songwhipApi/types';
import Box from '~/src/components/Box';
import { CARD_STYLE } from '~/src/components/Card';
import Clickable from '~/src/components/Clickable';
import CopyIconWrapper from '~/src/components/Icon/CopyIcon';
import Loading from '~/src/components/Loading';
import { useAppToast } from '~/src/components/NextApp/lib/CoreUi';
import { DataTable } from '~/src/components/Table';
import Text from '~/src/components/Text';
import { useApi } from '~/src/hooks/useApi';
import { useI18nDynamic } from '~/src/lib/i18n';
import { getChannelsApi } from '~/src/lib/songwhipApi/accounts/channels';
import copyToClipboard from '~/src/lib/utils/copyToClipboard';
import { Layout } from '~/src/ui/layouts/layout';
import { ChannelCell } from './ChannelCell';
import { EmptyState } from './EmptyState';
import { ErrorState } from './ErrorState';
import { createChannelLink } from './utils';

export const ChannelsTable = ({
  contentLink,
  channelFilter,
}: {
  contentLink: MappedContentLink;
  channelFilter: string;
}) => {
  const {
    data: channels,
    isLoading,
    error,
    mutate: refetch,
  } = useApi(
    getChannelsApi,
    [{ accountId: contentLink.ownedByAccounts[0].id }],
    { revalidateOnFocus: false }
  );

  const { t } = useI18nDynamic('contentLink');
  const appToast = useAppToast();
  const baseUrl = `https://${contentLink.customLink.domain}${contentLink.customLink.path}`;

  const copyLink = async (code?: string) => {
    await copyToClipboard(code ? createChannelLink(baseUrl, code) : baseUrl);

    appToast({
      timeoutSecs: 2,
      text: t('actions.linkCopied'),
    });
  };

  const columns: DataTableColumn<SongwhipChannel>[] = [
    {
      key: 'channel',
      header: t('channels.colChannel'),
      renderCell: ({ code, name }) => (
        <ChannelCell code={code} name={name} baseUrl={baseUrl} />
      ),
    },
    {
      key: 'medium',
      header: t('channels.colMedium'),
      width: '30%',
      renderCell: ({ medium }) => {
        const text = {
          [SongwhipChannelMediums.PAID]: t('channels.mediumPaid'),
          [SongwhipChannelMediums.OWNED]: t('channels.mediumOwned'),
        };

        return (
          <Text size="1.3rem" withEllipsis>
            {text[medium]}
          </Text>
        );
      },
    },
    {
      key: 'actions',
      header: '',
      width: '5.6rem',
      align: 'right',
      renderCell: ({ code }) => (
        <Clickable
          testId="copyChannelLinkButton"
          fullWidth
          fullHeight
          centerContent
          onClick={() => {
            copyLink(code);
          }}
        >
          <CopyIconWrapper size="2.4rem" color="#888" />
        </Clickable>
      ),
    },
  ];

  const filteredChannels = channelFilter
    ? channels?.filter(({ code, name }) => {
        const searchValue = channelFilter.toLowerCase();

        return (
          code.toLowerCase().includes(searchValue) ||
          name.toLowerCase().includes(searchValue)
        );
      })
    : channels;

  const hasChannels = !!channels?.length;

  return (
    <Layout column gap="6">
      <DataTable
        testId="channelsTable"
        columns={columns}
        rows={filteredChannels ?? []}
        getRowKey={({ id }) => String(id)}
        maxHeight="32rem"
        renderState={({ isEmpty }) => {
          if (error) {
            return <ErrorState error={error} onRetry={refetch} />;
          }

          if (isLoading) {
            return (
              <Layout column align="center" justify="center" minHeight="6rem">
                <Loading />
              </Layout>
            );
          }

          if (isEmpty) {
            return <EmptyState hasChannels={hasChannels} />;
          }

          return null;
        }}
        renderAfter={() => {
          return (
            <Box
              flexRow
              alignCenter
              gap="1rem"
              minWidth={0}
              padding="1.4rem 1.6rem"
              style={{
                borderTop: CARD_STYLE.border,
                background: '#111',
              }}
            >
              <Box flexColumn flexGrow gap="0.2rem" minWidth={0}>
                <Text size="1.3rem" weight="medium">
                  {t('channels.noChannel')}
                </Text>
                <Text
                  title={baseUrl}
                  size="1.3rem"
                  color="#B2B2B2"
                  withEllipsis
                  noWrap
                >
                  {baseUrl}
                </Text>
              </Box>
              <Box noFlexShrink centerContent>
                <Clickable
                  centerContent
                  onClick={() => {
                    copyLink();
                  }}
                >
                  <CopyIconWrapper size="2.4rem" color="#888" />
                </Clickable>
              </Box>
            </Box>
          );
        }}
      />
    </Layout>
  );
};
