import { Navigate, useParams } from 'react-router';
import type { LayoutNode } from 'officerdev';
import {
  WorkspaceView,
  DEFAULT_TRANSMISSION_SECTION,
  transmissionSectionPath,
  isTransmissionSection,
} from 'officerdev';
import { useDashboardState } from 'state/useDashboardState';
import { defaultLayout } from './defaultLayout';

// /transmission uses the Workspace/Panel system (like /headscale): a filter nav on the left and the section
// view on the right. Both talk to the officer-transmission sidecar through the /api/transmission auth proxy,
// which holds no Transmission credentials of its own — the RPC URL and any Basic auth live in the sidecar.
//
// The open section is :section in the URL and the torrent filters are query params, so both panels read the
// URL with useParams/useSearchParams instead of passing state between themselves over a channel. This screen
// backs both /transmission and /transmission/:section and is the single place that decides what an absent or
// bogus section means.

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

  // Bare /transmission, 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 (!isTransmissionSection(section)) {
    return <Navigate to={transmissionSectionPath(DEFAULT_TRANSMISSION_SECTION)} replace />;
  }

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