import { useTranslation } from 'react-i18next';
import { useLiveKeyString, useModule, useStatus } from '~/lib/react';
import { useAppDispatch, useAppSelector } from '~/store';
import apiReducer, { modules } from '~/store/api/reducer';
import { startAuthFlow } from '~/lib/twitch';
import TwitchUserBlock from '~/ui/components/TwitchUserBlock';
import { ExternalLinkIcon } from '@radix-ui/react-icons';
import SaveButton from '../../components/forms/SaveButton';
import {
  Button,
  Field,
  FlexRow,
  InputBox,
  Label,
  SectionHeader,
  TextBlock,
} from '../../theme';

export default function TwitchChatSettings() {
  const [chatConfig, setChatConfig, loadStatus] = useModule(
    modules.twitchChatConfig,
  );
  const kv = useAppSelector((state) => state.api.client);
  const authKey = 'twitch/chat/chatter-account';
  const authKeyValue = useLiveKeyString('twitch/chat/chatter-account');
  const status = useStatus(loadStatus.save);
  const dispatch = useAppDispatch();
  const { t } = useTranslation();
  const disabled = status?.type === 'pending';

  return (
    <form
      onSubmit={(ev) => {
        void dispatch(setChatConfig(chatConfig));
        ev.preventDefault();
      }}
    >
      <SectionHeader spacing={'none'}>
        {t('pages.twitch-settings.chat.chat-account')}
      </SectionHeader>
      <TextBlock>{t('pages.twitch-settings.chat.account-copy')}</TextBlock>
      <FlexRow align="left" spacing="1" css={{ marginBottom: '1rem' }}>
        <Button
          variation="primary"
          type="button"
          onClick={() => {
            void startAuthFlow('chat');
          }}
        >
          <ExternalLinkIcon /> {t('pages.twitch-settings.events.auth-button')}
        </Button>
        {authKeyValue && (
          <Button
            variation="danger"
            type="button"
            onClick={() => {
              kv.deleteKey(authKey);
            }}
          >
            {t('pages.twitch-settings.chat.clear-button')}
          </Button>
        )}
      </FlexRow>
      <TwitchUserBlock
        authKey={'twitch/chat/chatter-account'}
        noUserMessage={t('pages.twitch-settings.chat.default-user')}
      />

      <SectionHeader>{t('pages.twitch-settings.chat.header')}</SectionHeader>
      <Field size="fullWidth">
        <Label htmlFor="bot-chat-history">
          {t('pages.twitch-settings.chat.cooldown-tip')}
        </Label>
        <InputBox
          type="number"
          id="bot-chat-history"
          required={true}
          disabled={disabled}
          defaultValue={
            chatConfig ? chatConfig.command_cooldown ?? 2 : undefined
          }
          onChange={(ev) =>
            dispatch(
              apiReducer.actions.twitchChatConfigChanged({
                ...chatConfig,
                command_cooldown: parseInt(ev.target.value, 10),
              }),
            )
          }
        />
      </Field>
      <SaveButton status={status} />
    </form>
  );
}
