import React, { useCallback } from 'react';
import { MatrixError, Room as MatrixRoom } from 'matrix-js-sdk';
import { useTranslation } from 'react-i18next';
import { Box, Button, Icon, Icons, Spinner, Text, color } from 'folds';
import type { BotPreset } from '../../../features/bots/catalog';
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { BotOpenChatAction } from './BotOpenChatAction';
import { BotStatePage } from './BotStatePage';

type BotKickedProps = {
  preset: BotPreset;
  room: MatrixRoom;
};

export function BotKicked({ preset, room }: BotKickedProps) {
  const { t } = useTranslation();
  const mx = useMatrixClient();

  // Re-invite the bot back into the existing control DM. useBotRoom will
  // re-classify on the resulting RoomStateEvent.Members and transition the
  // experience host to bot-invite → ready without minting a new room.
  const [reinviteState, reinvite] = useAsyncCallback<void, Error | MatrixError, []>(
    useCallback(async () => {
      await mx.invite(room.roomId, preset.mxid);
    }, [mx, room, preset])
  );

  const loading = reinviteState.status === AsyncStatus.Loading;
  const error = reinviteState.status === AsyncStatus.Error ? reinviteState.error : undefined;

  return (
    <BotStatePage
      icon={<Icon size="600" src={Icons.Warning} />}
      title={t('Bots.kicked_title', { name: preset.name })}
      description={t('Bots.kicked_description', { mxid: preset.mxid })}
    >
      {error && (
        <Box style={{ color: color.Critical.Main }} alignItems="Center" gap="200">
          <Icon src={Icons.Warning} filled size="100" />
          <Text size="T300" style={{ color: color.Critical.Main }}>
            <b>{error.message || t('Bots.reinvite_error')}</b>
          </Text>
        </Box>
      )}
      <Button
        variant="Primary"
        size="500"
        radii="400"
        onClick={() => reinvite().catch(() => undefined)}
        disabled={loading}
        before={loading && <Spinner variant="Primary" fill="Solid" size="200" />}
      >
        <Text size="B500">{t('Bots.reinvite', { name: preset.name })}</Text>
      </Button>
      <BotOpenChatAction room={room} />
    </BotStatePage>
  );
}
