import React, { MouseEventHandler, useState } from 'react';
import FocusTrap from 'focus-trap-react';
import { Box, Chip, Menu, MenuItem, PopOut, RectCords, Text, config } from 'folds';
import { Icon, Icons } from '../../components/icons';
import type { HierarchyItem } from '../../hooks/useSpaceHierarchy';
import { useOpenCreateRoomModal } from '../../state/hooks/createRoomModal';
import { useOpenCreateSpaceModal } from '../../state/hooks/createSpaceModal';
import { AddExistingModal } from '../add-existing';
import { stopPropagation } from '../../utils/keyboard';

function AddRoomButton({ item, roomLabel }: { item: HierarchyItem; roomLabel?: string }) {
  const [cords, setCords] = useState<RectCords>();
  const openCreateRoomModal = useOpenCreateRoomModal();
  const [addExisting, setAddExisting] = useState(false);

  const handleAddRoom: MouseEventHandler<HTMLButtonElement> = (evt) => {
    setCords(evt.currentTarget.getBoundingClientRect());
  };

  const handleCreateRoom = () => {
    openCreateRoomModal(item.roomId);
    setCords(undefined);
  };

  const handleAddExisting = () => {
    setAddExisting(true);
    setCords(undefined);
  };

  return (
    <>
      <PopOut
        anchor={cords}
        position="Bottom"
        align="Start"
        content={
          <FocusTrap
            focusTrapOptions={{
              initialFocus: false,
              onDeactivate: () => setCords(undefined),
              clickOutsideDeactivates: true,
              isKeyForward: (evt: KeyboardEvent) => evt.key === 'ArrowDown',
              isKeyBackward: (evt: KeyboardEvent) => evt.key === 'ArrowUp',
              escapeDeactivates: stopPropagation,
            }}
          >
            <Menu style={{ padding: config.space.S100 }}>
              <MenuItem
                size="300"
                radii="300"
                variant="Primary"
                fill="None"
                onClick={handleCreateRoom}
              >
                <Text size="T300">New Room</Text>
              </MenuItem>
              <MenuItem size="300" radii="300" fill="None" onClick={handleAddExisting}>
                <Text size="T300">Existing Room</Text>
              </MenuItem>
            </Menu>
          </FocusTrap>
        }
      >
        <Chip
          variant="Primary"
          radii="Pill"
          before={<Icon src={Icons.Plus} size="50" />}
          onClick={handleAddRoom}
          aria-pressed={!!cords}
        >
          <Text size="B300">{roomLabel ?? 'Add Room'}</Text>
        </Chip>
      </PopOut>
      {addExisting && (
        <AddExistingModal parentId={item.roomId} requestClose={() => setAddExisting(false)} />
      )}
    </>
  );
}

function AddSpaceButton({ item, spaceLabel }: { item: HierarchyItem; spaceLabel?: string }) {
  const [cords, setCords] = useState<RectCords>();
  const openCreateSpaceModal = useOpenCreateSpaceModal();
  const [addExisting, setAddExisting] = useState(false);

  const handleAddSpace: MouseEventHandler<HTMLButtonElement> = (evt) => {
    setCords(evt.currentTarget.getBoundingClientRect());
  };

  const handleCreateSpace = () => {
    openCreateSpaceModal(item.roomId as string);
    setCords(undefined);
  };

  const handleAddExisting = () => {
    setAddExisting(true);
    setCords(undefined);
  };

  return (
    <>
      <PopOut
        anchor={cords}
        position="Bottom"
        align="Start"
        content={
          <FocusTrap
            focusTrapOptions={{
              initialFocus: false,
              onDeactivate: () => setCords(undefined),
              clickOutsideDeactivates: true,
              isKeyForward: (evt: KeyboardEvent) => evt.key === 'ArrowDown',
              isKeyBackward: (evt: KeyboardEvent) => evt.key === 'ArrowUp',
              escapeDeactivates: stopPropagation,
            }}
          >
            <Menu style={{ padding: config.space.S100 }}>
              <MenuItem
                size="300"
                radii="300"
                variant="Primary"
                fill="None"
                onClick={handleCreateSpace}
              >
                <Text size="T300">New Space</Text>
              </MenuItem>
              <MenuItem size="300" radii="300" fill="None" onClick={handleAddExisting}>
                <Text size="T300">Existing Space</Text>
              </MenuItem>
            </Menu>
          </FocusTrap>
        }
      >
        <Chip
          variant="SurfaceVariant"
          radii="Pill"
          before={<Icon src={Icons.Plus} size="50" />}
          onClick={handleAddSpace}
          aria-pressed={!!cords}
        >
          <Text size="B300">{spaceLabel ?? 'Add Space'}</Text>
        </Chip>
      </PopOut>
      {addExisting && (
        <AddExistingModal space parentId={item.roomId} requestClose={() => setAddExisting(false)} />
      )}
    </>
  );
}

type SpaceAddControlsProps = {
  item: HierarchyItem;
  /** Show “Add Space” (root / top-level space only). */
  showAddSpace?: boolean;
  roomLabel?: string;
  spaceLabel?: string;
};

/** Add room / add sub-space chips from the space lobby. */
export function SpaceAddControls({
  item,
  showAddSpace = false,
  roomLabel,
  spaceLabel,
}: SpaceAddControlsProps) {
  return (
    <Box direction="Row" alignItems="Center" gap="200">
      <AddRoomButton item={item} roomLabel={roomLabel} />
      {showAddSpace && <AddSpaceButton item={item} spaceLabel={spaceLabel} />}
    </Box>
  );
}
