import { ExternalLinkIcon } from '@radix-ui/react-icons';
import { useTranslation } from 'react-i18next';
import eventsubTests from '~/data/eventsub-tests';
import { useAppSelector } from '~/store';
import { startAuthFlow } from '~/lib/twitch';
import { Button, ButtonGroup, SectionHeader, TextBlock } from '../../theme';
import TwitchUserBlock from '../../components/TwitchUserBlock';

export default function TwitchEventSubSettings() {
  const { t } = useTranslation();
  const kv = useAppSelector((state) => state.api.client);

  const sendFakeEvent = async (event: keyof typeof eventsubTests) => {
    const data = eventsubTests[event];
    await kv.putJSON(`twitch/ev/eventsub-event/${event}`, {
      ...data,
      subscription: {
        ...data.subscription,
        created_at: new Date().toISOString(),
      },
      date: new Date().toISOString(),
    });
  };

  return (
    <>
      <TextBlock>{t('pages.twitch-settings.events.auth-message')}</TextBlock>
      <Button
        variation="primary"
        onClick={() => {
          void startAuthFlow('stream');
        }}
      >
        <ExternalLinkIcon /> {t('pages.twitch-settings.events.auth-button')}
      </Button>
      <SectionHeader>
        {t('pages.twitch-settings.events.current-status')}
      </SectionHeader>
      <TwitchUserBlock
        authKey={'twitch/auth-keys'}
        noUserMessage={t('pages.twitch-settings.events.err-no-user')}
      />
      <SectionHeader>
        {t('pages.twitch-settings.events.sim-events')}
      </SectionHeader>
      <ButtonGroup>
        {Object.keys(eventsubTests).map((ev: keyof typeof eventsubTests) => (
          <Button
            key={ev}
            onClick={() => {
              void sendFakeEvent(ev);
            }}
          >
            {t(`pages.twitch-settings.events.sim.${ev}`, { defaultValue: ev })}
          </Button>
        ))}
      </ButtonGroup>
    </>
  );
}
