import React, { useEffect } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { Box, Icon, IconButton, Icons, Scroll, Text, config } from 'folds';
import { useTranslation } from 'react-i18next';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { getDirectCreateSearchParams } from '../../pathSearchParam';
import { getDirectRoomPath } from '../../pathUtils';
import { getDMRoomFor } from '../../../utils/matrix';
import { useDirectRooms } from './useDirectRooms';
import { Page, PageContent, PageContentCenter, PageHeader } from '../../../components/page';
import { BackRouteHandler } from '../../../components/BackRouteHandler';
import { CreateChat } from '../../../features/create-chat';

export function DirectCreate() {
  const { t } = useTranslation();
  const mx = useMatrixClient();

  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const { userId } = getDirectCreateSearchParams(searchParams);

  const directs = useDirectRooms();

  useEffect(() => {
    if (userId) {
      const roomId = getDMRoomFor(mx, userId)?.roomId;
      if (roomId && directs.includes(roomId)) {
        navigate(getDirectRoomPath(roomId), { replace: true });
      }
    }
  }, [mx, navigate, directs, userId]);

  // One Dawn layout for every size: a left-aligned back-chevron header over the
  // grouped CreateChat block in a padded Scroll. This explicit create-by-id
  // surface backs the `/u/<user>` deep link (UserLinkRedirect) and the Direct
  // empty-state CTA; the everyday way to start a chat is the search People
  // section. No centered hero — the keyboard no longer fights an oversized hero
  // on short native viewports.
  return (
    <Page>
      <PageHeader balance outlined={false}>
        <Box grow="Yes" alignItems="Center" gap="200">
          <BackRouteHandler>
            {(onBack) => (
              <IconButton onClick={onBack}>
                <Icon src={Icons.ArrowLeft} />
              </IconButton>
            )}
          </BackRouteHandler>
          <Text size="H4" truncate>
            {t('Direct.create_chat')}
          </Text>
        </Box>
      </PageHeader>
      <Box grow="Yes">
        <Scroll hideTrack visibility="Hover">
          <PageContent>
            <PageContentCenter>
              <Box style={{ paddingTop: config.space.S200 }}>
                <CreateChat defaultUserId={userId} />
              </Box>
            </PageContentCenter>
          </PageContent>
        </Scroll>
      </Box>
    </Page>
  );
}
