import type { ReactNode } from "react";
import { EyeOff } from "lucide-react";
import type { ApiSettings, ViewsRuntimeUiCapability } from "../types";
import { useEffectiveView, useViewSurfaceVisible } from "../platform/ViewContext";
import { dispatchPlatformViewChanged } from "../platform/views";
import { useGuardedNavigate } from "./UnsavedChangesGuard";
import Button from "./Button";
import Card from "./Card";
import PageScrollViewport from "./PageScrollViewport";

export default function ViewSurfaceRouteBoundary({
  surfaceId,
  settings,
  runtime,
  fallbackPath,
  children
}: {
  surfaceId?: string;
  settings: ApiSettings;
  runtime: ViewsRuntimeUiCapability | null;
  fallbackPath: string;
  children: ReactNode;
}) {
  const visible = useViewSurfaceVisible(surfaceId);
  const projection = useEffectiveView();
  const navigate = useGuardedNavigate();

  if (visible) return <>{children}</>;

  async function exitView() {
    if (!runtime || projection?.locked) return;
    await runtime.activateView(settings, null);
    dispatchPlatformViewChanged();
  }

  return (
    <PageScrollViewport>
      <div className="content-pad">
        <Card title="Outside the current view">
          <div className="empty-state">
            <EyeOff size={24} aria-hidden="true" />
            <p>
              This area is available to your account, but hidden by
              {projection?.activeViewName
                ? ` the ${projection.activeViewName} view`
                : " the current view"}.
            </p>
            <div className="button-row">
              {!projection?.locked && runtime && (
                <Button variant="primary" onClick={() => void exitView()}>
                  Exit view
                </Button>
              )}
              <Button onClick={() => navigate(fallbackPath)}>Back to view</Button>
            </div>
          </div>
        </Card>
      </div>
    </PageScrollViewport>
  );
}
