import React, { useState } from 'react';
import {
  Box,
  Header,
  Icon,
  IconButton,
  Icons,
  Overlay,
  OverlayBackdrop,
  OverlayCenter,
  Text,
  color,
  config,
} from 'folds';
import FocusTrap from 'focus-trap-react';
import { useTranslation } from 'react-i18next';
import { isAndroidPlatform } from '../../utils/capacitor';
import { stopPropagation } from '../../utils/keyboard';
import { ProxyForm } from '../../features/settings/network';
import * as css from './styles.css';

/**
 * Pre-login proxy entry (proxy_android_impl.md §2, F1). Because creds are
 * wiped on logout, a blocked re-login must be able to configure a proxy
 * BEFORE authenticating — this is the headline censorship case. Rendered as
 * a self-contained overlay so it never touches the bistable auth-layout CSS
 * (bugs.md). Android-only; renders nothing elsewhere.
 *
 * No homeserver base URL is known yet pre-login, so the override routes all
 * traffic during discovery; the authed boot path narrows it to the resolved
 * homeserver host once logged in (applyAtBoot in index boot).
 */
export function ProxySettingsEntry() {
  const { t } = useTranslation();
  const [open, setOpen] = useState(false);

  if (!isAndroidPlatform()) return null;

  return (
    <>
      <button type="button" className={css.AuthProxyEntry} onClick={() => setOpen(true)}>
        {t('Settings.network.pre_login_entry')}
      </button>
      <Overlay open={open} backdrop={<OverlayBackdrop />}>
        <OverlayCenter>
          <FocusTrap
            focusTrapOptions={{
              initialFocus: false,
              onDeactivate: () => setOpen(false),
              clickOutsideDeactivates: true,
              escapeDeactivates: stopPropagation,
            }}
          >
            <Box
              direction="Column"
              style={{
                maxWidth: '28rem',
                width: '100%',
                maxHeight: '85vh',
                backgroundColor: color.SurfaceVariant.Container,
                borderRadius: config.radii.R400,
              }}
            >
              <Header
                size="500"
                style={{ paddingLeft: config.space.S400, paddingRight: config.space.S200 }}
              >
                <Box grow="Yes">
                  <Text size="H4">{t('Settings.network.pre_login_title')}</Text>
                </Box>
                <IconButton size="300" radii="300" onClick={() => setOpen(false)}>
                  <Icon src={Icons.Cross} />
                </IconButton>
              </Header>
              <Box
                grow="Yes"
                direction="Column"
                style={{ padding: config.space.S400, overflowY: 'auto' }}
              >
                <ProxyForm compact />
              </Box>
            </Box>
          </FocusTrap>
        </OverlayCenter>
      </Overlay>
    </>
  );
}
