import React, { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { useAtomValue } from 'jotai';
import { Box, Icon, Icons, Scroll, Text, color, config, toRem } from 'folds';
import { Room } from 'matrix-js-sdk';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { allRoomsAtom } from '../../../state/room-list/roomList';
import { roomToParentsAtom } from '../../../state/room/roomToParents';
import { useOrphanSpaces } from '../../../state/hooks/roomList';
import { useRoomName } from '../../../hooks/useRoomMeta';
import { useOpenCreateSpaceModal } from '../../../state/hooks/createSpaceModal';
import { getCanonicalAliasOrRoomId } from '../../../utils/matrix';
import { getChannelsSpacePath } from '../../pathUtils';
import { NavButton, NavItem, NavItemContent } from '../../../components/nav';
import { SpaceAvatar } from './SpaceAvatar';
import { CreateCommunityTile } from './WorkspaceSwitcherSheet.css';

const ROW_MIN_HEIGHT = toRem(60);

type CreateCommunityRowProps = {
  onClick: () => void;
};

// Top action of the sheet. The row uses `variant="SurfaceVariant"` so
// its card bg matches the sheet's silhouette bg
// (`SurfaceVariant.Container` = #181a20 — see
// `ChannelsWorkspaceHorseshoe.css.ts::silhouette`) instead of the
// darker `Background.Container` the data rows below use. Result: the
// «create» row blends into the sheet surface (no visible card
// outline), while space rows stay as distinct list-item cards. The
// leading `+` is a bare icon centred in the same 40-wide slot the
// space rows use for `SpaceAvatar`, so the text columns align.
function CreateCommunityRow({ onClick }: CreateCommunityRowProps) {
  const { t } = useTranslation();
  return (
    <NavItem variant="SurfaceVariant" radii="400" style={{ minHeight: ROW_MIN_HEIGHT }}>
      <NavButton onClick={onClick} aria-label={t('Channels.workspace_switcher_create_space')}>
        <NavItemContent>
          <Box
            as="span"
            grow="Yes"
            alignItems="Center"
            gap="300"
            style={{
              minHeight: ROW_MIN_HEIGHT,
              boxSizing: 'border-box',
              padding: `${toRem(6)} 0`,
            }}
          >
            <span className={CreateCommunityTile}>
              <Icon src={Icons.Plus} size="300" />
            </span>
            <Box as="span" grow="Yes" style={{ minWidth: 0 }}>
              <Text as="span" size="T300" truncate style={{ fontWeight: 600 }}>
                {t('Channels.workspace_switcher_create_space')}
              </Text>
            </Box>
          </Box>
        </NavItemContent>
      </NavButton>
    </NavItem>
  );
}

type SpaceRowProps = {
  space: Room;
  isActive: boolean;
  onPick: (spaceId: string) => void;
};

// One space row in the sheet. Mirrors the DM-row visual: avatar 40,
// two text lines (name + member-count subtitle). Variant is
// `SurfaceVariant` so the inactive row bg (`SurfaceVariant.Container`
// = #181a20) matches the sheet silhouette and blends into it — same
// treatment as `CreateCommunityRow` above. The active community is
// signalled solely via `aria-selected` → `ContainerActive` (#2a2d36),
// which lifts cleanly off the sheet without a card outline; an
// explicit trailing label was tried and dropped per product call.
//
// `useRoomName` lives here so the per-space subscription stays scoped
// (Rules of Hooks) and admin renames reflect in the dropdown without
// a parent re-render.
function SpaceRow({ space, isActive, onPick }: SpaceRowProps) {
  const { t } = useTranslation();
  const name = useRoomName(space);
  const memberCount = space.getJoinedMemberCount();

  return (
    <NavItem
      variant="SurfaceVariant"
      radii="400"
      aria-selected={isActive}
      style={{ minHeight: ROW_MIN_HEIGHT }}
    >
      <NavButton onClick={() => onPick(space.roomId)}>
        <NavItemContent>
          <Box
            as="span"
            grow="Yes"
            alignItems="Center"
            gap="300"
            style={{
              minHeight: ROW_MIN_HEIGHT,
              boxSizing: 'border-box',
              padding: `${toRem(6)} 0`,
            }}
          >
            <SpaceAvatar space={space} size={40} />
            <Box
              as="span"
              direction="Column"
              grow="Yes"
              gap="100"
              style={{ minWidth: 0, overflow: 'hidden' }}
            >
              <Text as="span" size="T300" truncate style={{ fontWeight: 600 }}>
                {name}
              </Text>
              <Text as="span" size="T200" truncate style={{ opacity: 0.6 }}>
                {t('Channels.workspace_switcher_member_count', { count: memberCount })}
              </Text>
            </Box>
          </Box>
        </NavItemContent>
      </NavButton>
    </NavItem>
  );
}

type WorkspaceSwitcherSheetProps = {
  space: Room;
  requestClose: () => void;
};

// In-sheet workspace switcher panel. Top: «Create community» row +
// separator. Bottom: scrollable list of orphan spaces styled like the
// DM list (NavItem-Background rows, `aria-selected` for the active
// community — no harsh inset ring). `requestClose` is plumbed from
// the horseshoe via the canonical `closeSheetRef.current()` indirection
// so any picker action collapses the sheet on its way out.
export function WorkspaceSwitcherSheet({ space, requestClose }: WorkspaceSwitcherSheetProps) {
  const mx = useMatrixClient();
  const navigate = useNavigate();
  const roomToParents = useAtomValue(roomToParentsAtom);
  const orphanSpaceIds = useOrphanSpaces(mx, allRoomsAtom, roomToParents);
  const openCreateSpaceModal = useOpenCreateSpaceModal();

  const handlePickSpace = useCallback(
    (spaceId: string) => {
      requestClose();
      if (spaceId === space.roomId) return;
      const idOrAlias = getCanonicalAliasOrRoomId(mx, spaceId);
      navigate(getChannelsSpacePath(idOrAlias));
    },
    [requestClose, mx, navigate, space.roomId]
  );

  const handleCreateSpace = useCallback(() => {
    requestClose();
    openCreateSpaceModal();
  }, [requestClose, openCreateSpaceModal]);

  return (
    <Scroll
      variant="SurfaceVariant"
      size="300"
      hideTrack
      style={{ flex: 1, minHeight: 0, minWidth: 0 }}
    >
      <Box
        direction="Column"
        gap="100"
        style={{
          padding: `${config.space.S100} ${config.space.S200} ${config.space.S300}`,
        }}
      >
        <CreateCommunityRow onClick={handleCreateSpace} />
        <div
          aria-hidden
          style={{
            height: toRem(1),
            background: color.Surface.ContainerLine,
            margin: `${config.space.S100} ${config.space.S100}`,
          }}
        />
        {orphanSpaceIds.map((spaceId) => {
          const r = mx.getRoom(spaceId);
          if (!r) return null;
          return (
            <SpaceRow
              key={spaceId}
              space={r}
              isActive={spaceId === space.roomId}
              onPick={handlePickSpace}
            />
          );
        })}
      </Box>
    </Scroll>
  );
}
