import React, { useMemo, useState } from 'react';
import { Avatar, Box, Icon, IconButton, Icons, IconSrc, Text } from 'folds';
import { JoinRule } from 'matrix-js-sdk';
import { useTranslation } from 'react-i18next';
import { PageNav, PageNavContent, PageNavHeader, PageRoot } from '../../components/page';
import {
  SettingsNavEyebrow,
  SettingsNavItem,
  SettingsNavSection,
} from '../common-settings/SettingsNav';
import { ScreenSize, useScreenSizeContext } from '../../hooks/useScreenSize';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { mxcUrlToHttp } from '../../utils/matrix';
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
import { useRoomAvatar, useRoomJoinRule, useRoomName } from '../../hooks/useRoomMeta';
import { isOneOnOneRoom } from '../../utils/room';
import { RoomAvatar, RoomIcon } from '../../components/room-avatar';
import { SpaceSettingsPage } from '../../state/spaceSettings';
import { useRoom } from '../../hooks/useRoom';
import { EmojisStickers } from '../common-settings/emojis-stickers';
import { Members } from '../common-settings/members';
import { DeveloperTools } from '../common-settings/developer-tools';
import { General } from './general';
import { Permissions } from './permissions';

type SpaceSettingsMenuItem = {
  page: SpaceSettingsPage;
  name: string;
  icon: IconSrc;
};

const useSpaceSettingsMenuItems = (): SpaceSettingsMenuItem[] => {
  const { t } = useTranslation();
  return useMemo(
    () => [
      {
        page: SpaceSettingsPage.GeneralPage,
        name: t('RoomSettings.general'),
        icon: Icons.Setting,
      },
      {
        page: SpaceSettingsPage.MembersPage,
        name: t('RoomSettings.members'),
        icon: Icons.User,
      },
      {
        page: SpaceSettingsPage.PermissionsPage,
        name: t('RoomSettings.permissions'),
        icon: Icons.Lock,
      },
      {
        page: SpaceSettingsPage.EmojisStickersPage,
        name: t('RoomSettings.emojis_stickers'),
        icon: Icons.Smile,
      },
      {
        page: SpaceSettingsPage.DeveloperToolsPage,
        name: t('RoomSettings.developer_tools'),
        icon: Icons.Terminal,
      },
    ],
    [t]
  );
};

type SpaceSettingsProps = {
  initialPage?: SpaceSettingsPage;
  requestClose: () => void;
};
export function SpaceSettings({ initialPage, requestClose }: SpaceSettingsProps) {
  const { t } = useTranslation();
  const room = useRoom();
  const mx = useMatrixClient();
  const useAuthentication = useMediaAuthentication();

  // `isOneOnOneRoom` excludes spaces, so this resolves to `false` for the
  // space-settings drawer — kept on the helper for symmetry with RoomSettings.
  const roomAvatar = useRoomAvatar(room, isOneOnOneRoom(room));
  const roomName = useRoomName(room);
  const joinRuleContent = useRoomJoinRule(room);

  const avatarUrl = roomAvatar
    ? mxcUrlToHttp(mx, roomAvatar, useAuthentication, 96, 96, 'crop') ?? undefined
    : undefined;

  const screenSize = useScreenSizeContext();
  const [activePage, setActivePage] = useState<SpaceSettingsPage | undefined>(() => {
    if (initialPage) return initialPage;
    return screenSize === ScreenSize.Mobile ? undefined : SpaceSettingsPage.GeneralPage;
  });
  const menuItems = useSpaceSettingsMenuItems();

  const handlePageRequestClose = () => {
    if (screenSize === ScreenSize.Mobile) {
      setActivePage(undefined);
      return;
    }
    requestClose();
  };

  return (
    <PageRoot
      nav={
        screenSize === ScreenSize.Mobile && activePage !== undefined ? undefined : (
          <PageNav size="300">
            <PageNavHeader outlined={false}>
              <Box grow="Yes" gap="300" alignItems="Center">
                <Avatar size="300" radii="300">
                  <RoomAvatar
                    roomId={room.roomId}
                    src={avatarUrl}
                    alt={roomName}
                    renderFallback={() => (
                      <RoomIcon
                        roomType={room.getType()}
                        size="50"
                        joinRule={joinRuleContent?.join_rule ?? JoinRule.Invite}
                        filled
                      />
                    )}
                  />
                </Avatar>
                <Box direction="Column" grow="Yes">
                  <SettingsNavEyebrow>{t('RoomSettings.settings')}</SettingsNavEyebrow>
                  <Text size="H4" truncate>
                    {roomName}
                  </Text>
                </Box>
              </Box>
              <Box shrink="No">
                {screenSize === ScreenSize.Mobile && (
                  <IconButton onClick={requestClose} variant="Background">
                    <Icon src={Icons.Cross} />
                  </IconButton>
                )}
              </Box>
            </PageNavHeader>
            <Box grow="Yes" direction="Column">
              <PageNavContent>
                <div style={{ flexGrow: 1 }}>
                  <SettingsNavSection>{t('RoomSettings.sections')}</SettingsNavSection>
                  {menuItems.map((item) => (
                    <SettingsNavItem
                      key={item.name}
                      icon={item.icon}
                      label={item.name}
                      active={activePage === item.page}
                      onClick={() => setActivePage(item.page)}
                    />
                  ))}
                </div>
              </PageNavContent>
            </Box>
          </PageNav>
        )
      }
    >
      {activePage === SpaceSettingsPage.GeneralPage && (
        <General requestClose={handlePageRequestClose} />
      )}
      {activePage === SpaceSettingsPage.MembersPage && (
        <Members requestClose={handlePageRequestClose} />
      )}
      {activePage === SpaceSettingsPage.PermissionsPage && (
        <Permissions requestClose={handlePageRequestClose} />
      )}
      {activePage === SpaceSettingsPage.EmojisStickersPage && (
        <EmojisStickers requestClose={handlePageRequestClose} />
      )}
      {activePage === SpaceSettingsPage.DeveloperToolsPage && (
        <DeveloperTools requestClose={handlePageRequestClose} />
      )}
    </PageRoot>
  );
}
