import React, { useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import SettingsModal from '../settings/SettingsModal';
import { useAppShell } from '../appShellContext';
import useApiTokens from '../settings/useApiTokens';
import { api } from './appState';

const SettingsRoute = () => {
  const navigate = useNavigate();
  const {
    token,
    notifyApiError,
    setStatusMessage,
    passkeys,
    passkeysSupported,
    passkeysLoading,
    registeringPasskey,
    revokingPasskeyId,
    refreshPasskeys,
    registerPasskey,
    revokePasskey,
  } = useAppShell();

  const {
    tokens,
    loading,
    creating,
    deletingId,
    regeneratingId,
    updatingId,
    createdSecret,
    refresh,
    create,
    revoke,
    regenerate,
    updateCapabilities,
    dismissSecret,
  } = useApiTokens({ api, token, notifyApiError, setStatusMessage });

  useEffect(() => {
    refresh();
    refreshPasskeys();
  }, [refresh, refreshPasskeys]);

  const handleClose = useCallback(() => {
    dismissSecret();
    navigate(-1);
  }, [dismissSecret, navigate]);

  useEffect(() => {
    const handleKeyDown = (event) => {
      if (event.key === 'Escape') {
        event.preventDefault();
        handleClose();
      }
    };
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [handleClose]);

  useEffect(() => () => {
    dismissSecret();
  }, [dismissSecret]);

  return (
    <SettingsModal
      open
      onClose={handleClose}
      tokens={tokens}
      loading={loading}
      creating={creating}
      deletingId={deletingId}
      regeneratingId={regeneratingId}
      updatingId={updatingId}
      onRefresh={refresh}
      onCreate={create}
      onDelete={revoke}
      onRegenerate={regenerate}
      onUpdateCapabilities={updateCapabilities}
      createdToken={createdSecret}
      onDismissCreatedToken={dismissSecret}
      passkeys={passkeys}
      passkeysSupported={passkeysSupported}
      passkeysLoading={passkeysLoading}
      registeringPasskey={registeringPasskey}
      revokingPasskeyId={revokingPasskeyId}
      onRefreshPasskeys={refreshPasskeys}
      onRegisterPasskey={registerPasskey}
      onRevokePasskey={revokePasskey}
    />
  );
};

export default SettingsRoute;
