import React from 'react';
import { Navigate, useMatch, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useAtomValue } from 'jotai';
import { Box, Button, Icon, Icons, Text } from 'folds';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { allRoomsAtom } from '../../../state/room-list/roomList';
import { useOrphanSpaces } from '../../../state/hooks/roomList';
import { useOpenCreateSpaceModal } from '../../../state/hooks/createSpaceModal';
import { roomToParentsAtom } from '../../../state/room/roomToParents';
import { getCanonicalAliasOrRoomId } from '../../../utils/matrix';
import { CHANNELS_PATH } from '../../paths';
import { getChannelsSpacePath, getExplorePath } from '../../pathUtils';
import { NavEmptyCenter, NavEmptyLayout } from '../../../components/nav';
import { useActiveSpace } from './useActiveSpace';

// Index route for /channels/. Resolves the active Space (URL > localStorage >
// first joined orphan Space) and redirects there. If the user is in 0 orphan
// spaces, shows an empty state with a CTA to /explore/.
//
// The redirect is gated on `useMatch(CHANNELS_PATH, end:true)` because the
// mobile tab pager mounts this component as a side-by-side pane even while
// the URL still points at /direct/ or /bots/. Without the gate the
// `<Navigate replace>` here would fire on mount regardless of location (RR6
// runs Navigate's effect on mount of the element) and bounce the user out
// of their actual tab into the channels space on every cold-start.
export function ChannelsLanding() {
  const mx = useMatrixClient();
  const { t } = useTranslation();
  const navigate = useNavigate();
  const openCreateSpaceModal = useOpenCreateSpaceModal();
  const roomToParents = useAtomValue(roomToParentsAtom);
  const orphanSpaces = useOrphanSpaces(mx, allRoomsAtom, roomToParents);
  const activeSpaceId = useActiveSpace(orphanSpaces);
  const atChannelsRoot = !!useMatch({ path: CHANNELS_PATH, end: true });

  if (activeSpaceId && atChannelsRoot) {
    const spaceIdOrAlias = getCanonicalAliasOrRoomId(mx, activeSpaceId);
    return <Navigate to={getChannelsSpacePath(spaceIdOrAlias)} replace />;
  }
  // When the user has spaces but the pager mounted us in an off-screen
  // pane (URL is still /direct/ or /bots/), render nothing rather than
  // the «no spaces» empty state. The empty-state UI would mislead a
  // user who actually has spaces — they'd see «join a workspace» while
  // simply standing on the next tab over.
  if (activeSpaceId && !atChannelsRoot) {
    return null;
  }

  return (
    <NavEmptyCenter>
      <NavEmptyLayout
        icon={<Icon size="600" src={Icons.Hash} />}
        title={
          <Text size="H5" align="Center">
            {t('Channels.no_spaces_title')}
          </Text>
        }
        content={
          <Text size="T300" align="Center">
            {t('Channels.no_spaces_desc')}
          </Text>
        }
        options={
          <Box direction="Column" gap="200">
            <Button variant="Primary" size="300" onClick={() => navigate(getExplorePath())}>
              <Text size="B300" truncate>
                {t('Channels.explore_cta')}
              </Text>
            </Button>
            <Button
              variant="Secondary"
              fill="Soft"
              size="300"
              onClick={() => openCreateSpaceModal()}
            >
              <Text size="B300" truncate>
                {t('Channels.workspace_switcher_create_space')}
              </Text>
            </Button>
          </Box>
        }
      />
    </NavEmptyCenter>
  );
}
