import React from 'react';
import { useParams } from 'react-router-dom';
import { Icon, Icons } from 'folds';
import { useTranslation } from 'react-i18next';
import { useAtomValue } from 'jotai';
import type { Room as MatrixRoom } from 'matrix-js-sdk';
import {
  findBotPresetById,
  isAiChatExperience,
  useBotPresets,
  type BotPreset,
} from '../../../features/bots/catalog';
import { BotChatFallback } from '../../../features/bots/BotChatFallback';
import { BotConversations } from '../../../features/bots/BotConversations';
import { BotShell } from '../../../features/bots/BotShell';
import { botShowChatAtomFamily } from '../../../features/bots/botExperienceState';
import { useBotRoom } from '../../../features/bots/useBotRoom';
import { Room } from '../../../features/room';
import { BotInvitePending } from './BotInvitePending';
import { BotKicked } from './BotKicked';
import { BotNotConnected } from './BotNotConnected';
import { BotRoomProvider } from './BotRoomProvider';
import { BotStatePage } from './BotStatePage';
import { BotUnsafeRoom } from './BotUnsafeRoom';

// Picks the bot's experience. Two fully separate worlds, decided by `experience.type`:
//  - 'ai-chat' → the native conversation surface (BotConversations). Self-contained: its own
//    header/menu, NO widget, NO show-chat toggle. The showChat atom and the BotShell/chat-fallback
//    pipeline below are never reached for it.
//  - everything else (bridges) → the sandboxed widget (BotShell) with a "Show chat" fallback to
//    the standard Room layout, toggled by the per-room showChat atom (set from BotShellMenu).
// Lives inside BotRoomProvider so every arm sees the same room context.
function BotExperienceRoute({ preset, room }: { preset: BotPreset; room: MatrixRoom }) {
  // /bots/:botId/thread/:rootId carries the open conversation's thread root; bare
  // /bots/:botId leaves it undefined (the new-chat landing).
  const { rootId } = useParams();
  // Read unconditionally (rules of hooks); only the bridge path below consumes it.
  const showChat = useAtomValue(botShowChatAtomFamily(room.roomId));

  if (isAiChatExperience(preset.experience)) {
    return <BotConversations preset={preset} room={room} rootId={rootId} />;
  }
  if (showChat) {
    return <Room renderRoomView={({ eventId }) => <BotChatFallback eventId={eventId} />} />;
  }
  return <BotShell preset={preset} room={room} />;
}

export function BotExperienceHost() {
  const { t } = useTranslation();
  const { botId } = useParams();
  const bots = useBotPresets();
  const preset = findBotPresetById(bots, botId ?? '');
  const botRoomState = useBotRoom(preset);

  if (!preset) {
    return (
      <BotStatePage
        icon={<Icon size="600" src={Icons.Warning} />}
        title={t('Bots.unknown_title')}
        description={t('Bots.unknown_description')}
      />
    );
  }

  if (botRoomState.kind === 'none') {
    return <BotNotConnected preset={preset} />;
  }

  if (botRoomState.kind === 'self-invite') {
    return <BotInvitePending preset={preset} room={botRoomState.room} selfInvite />;
  }

  if (botRoomState.kind === 'bot-invite') {
    return <BotInvitePending preset={preset} room={botRoomState.room} />;
  }

  if (botRoomState.kind === 'bot-kicked') {
    return <BotKicked preset={preset} room={botRoomState.room} />;
  }

  if (botRoomState.kind === 'unsafe-membership') {
    return <BotUnsafeRoom room={botRoomState.room} />;
  }

  const { room } = botRoomState;

  return (
    <BotRoomProvider room={room}>
      <BotExperienceRoute preset={preset} room={room} />
    </BotRoomProvider>
  );
}
