import type { LayoutNode } from 'officerdev';
import { Navigate, useParams } from 'react-router';
import { DEFAULT_INVOICES_SECTION, invoicesSectionPath, isInvoicesSection, WorkspaceView } from 'officerdev';
import { useDashboardState } from 'state/useDashboardState';
import { defaultLayout } from './defaultLayout';

// /invoices uses the Workspace/Panel system (like /transmission and /headscale): the section nav on the
// left, the section itself on the right. Both panels talk to the officer-invoiceshelf sidecar through the
// /api/invoiceshelf auth proxy — the InvoiceShelf URL, its Sanctum token and the company header live in the
// sidecar and never reach the browser.
//
// The open section is :section in the URL; list filters, the selected record and the open editor are query
// params. So the panels read the URL rather than passing state to each other, and this screen is the single
// place that decides what an absent or bogus section means.

export const InvoicesScreen = () => {
  const { section } = useParams();
  const workspace = useDashboardState<LayoutNode>('screens/invoices', defaultLayout);

  // Bare /invoices, or a section that doesn't exist, resolves to a canonical URL rather than rendering a
  // default while the address bar says something else — the nav highlight is derived from the URL.
  if (!isInvoicesSection(section)) {
    return <Navigate to={invoicesSectionPath(DEFAULT_INVOICES_SECTION)} replace />;
  }

  return (
    <div className="h-full w-full pt-2">
      <WorkspaceView
        workspace={workspace}
        locked
        appTypes={{ allowed: ['invoices-nav', 'invoices-view'], fallback: 'invoices-view' }}
      />
    </div>
  );
};
