import React, { useState } from 'react';
import type { Room } from 'matrix-js-sdk';
import { Icon, IconButton, Icons, PopOut, RectCords, Tooltip, TooltipProvider, Text } from 'folds';
import FocusTrap from 'focus-trap-react';
import { useTranslation } from 'react-i18next';
import type { BotPreset } from './catalog';
import { AiChatMenu } from './AiChatMenu';
import { AiChatPrivacy } from './AiChatPrivacy';
import { BackRouteHandler } from '../../components/BackRouteHandler';
import { ScreenSize, useScreenSizeContext } from '../../hooks/useScreenSize';
import { stopPropagation } from '../../utils/keyboard';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
import { mxcUrlToHttp } from '../../utils/matrix';
// Reuse the bridge hero's EXACT styles so the AI header is pixel-identical to every other bot
// header (avatar 56px, name 22px, handle, description, mobile back chevron). The hero markup
// below mirrors BotShellHero verbatim — keep them in sync. Only the ⋮ menu differs (AiChatMenu).
import * as css from './BotShell.css';

// Initial for the avatar block — same rule as BotShellHero.
const heroInitial = (preset: BotPreset): string => {
  const fromName = preset.name.trim().charAt(0);
  if (fromName) return fromName.toUpperCase();
  const local = preset.mxid.split(':')[0].replace('@', '');
  return local.charAt(0).toUpperCase() || '?';
};

type AiChatHeaderProps = {
  preset: BotPreset;
  room: Room;
  onNewChat: () => void;
  onOpenHistory: () => void;
};

// Dedicated header for the native AI conversation surface. Renders the SAME hero as BotShellHero
// (shared BotShell.css), but is fully decoupled from the widget pipeline: its ⋮ opens AiChatMenu
// (New chat / History / Privacy & data / generic room actions) — no "Show chat", no widget toggle,
// no BotShellMenu. The privacy notice modal (AiChatPrivacy) is owned here too.
export function AiChatHeader({ preset, room, onNewChat, onOpenHistory }: AiChatHeaderProps) {
  const { t } = useTranslation();
  const mx = useMatrixClient();
  const useAuthentication = useMediaAuthentication();
  const screenSize = useScreenSizeContext();
  const isMobile = screenSize === ScreenSize.Mobile;
  const [menuAnchor, setMenuAnchor] = useState<RectCords>();
  const [privacyOpen, setPrivacyOpen] = useState(false);

  const avatarMxc = room.getMember(preset.mxid)?.getMxcAvatarUrl();
  const avatarUrl = avatarMxc
    ? mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96, 'crop') ?? undefined
    : undefined;

  const handleOpenMenu: React.MouseEventHandler<HTMLButtonElement> = (evt) => {
    setMenuAnchor(evt.currentTarget.getBoundingClientRect());
  };

  const description = t(`Bots.description.${preset.id}`, {
    defaultValue: preset.description ?? '',
  });
  const descriptionShort = t(`Bots.description_short.${preset.id}`, {
    defaultValue: description,
  });
  const initial = heroInitial(preset);

  return (
    <header className={css.Hero}>
      <div className={css.HeroInner}>
        {isMobile && (
          <BackRouteHandler>
            {(onBack) => (
              <IconButton
                className={css.HeroBack}
                fill="None"
                onClick={onBack}
                aria-label={t('Room.close')}
              >
                <Icon src={Icons.ChevronLeft} />
              </IconButton>
            )}
          </BackRouteHandler>
        )}
        <div className={css.HeroAvatar} aria-hidden="true">
          {avatarUrl ? <img className={css.HeroAvatarImg} src={avatarUrl} alt="" /> : initial}
        </div>
        <div className={css.HeroBody}>
          <div className={css.HeroTitleRow}>
            <span className={css.HeroName}>{preset.name}</span>
            <span className={css.HeroHandle}>{preset.mxid}</span>
          </div>
          {description ? <p className={css.HeroDescription}>{description}</p> : null}
          {descriptionShort ? <p className={css.HeroDescriptionShort}>{descriptionShort}</p> : null}
        </div>

        <TooltipProvider
          position="Bottom"
          align="End"
          offset={4}
          tooltip={
            <Tooltip>
              <Text>{t('Bots.more_options')}</Text>
            </Tooltip>
          }
        >
          {(triggerRef) => (
            <IconButton
              fill="None"
              ref={triggerRef}
              onClick={handleOpenMenu}
              aria-pressed={!!menuAnchor}
              aria-label={t('Bots.more_options')}
            >
              <Icon src={Icons.VerticalDots} filled={!!menuAnchor} />
            </IconButton>
          )}
        </TooltipProvider>
      </div>

      <PopOut
        anchor={menuAnchor}
        position="Bottom"
        align="End"
        content={
          <FocusTrap
            focusTrapOptions={{
              initialFocus: false,
              returnFocusOnDeactivate: false,
              onDeactivate: () => setMenuAnchor(undefined),
              clickOutsideDeactivates: true,
              isKeyForward: (evt: KeyboardEvent) => evt.key === 'ArrowDown',
              isKeyBackward: (evt: KeyboardEvent) => evt.key === 'ArrowUp',
              escapeDeactivates: stopPropagation,
            }}
          >
            <AiChatMenu
              room={room}
              requestClose={() => setMenuAnchor(undefined)}
              onNewChat={onNewChat}
              onOpenHistory={onOpenHistory}
              onOpenPrivacy={() => setPrivacyOpen(true)}
            />
          </FocusTrap>
        }
      />

      {privacyOpen && <AiChatPrivacy onClose={() => setPrivacyOpen(false)} />}
    </header>
  );
}
