import type { LayoutNode } from 'officerdev';
import { useSearchParams } from 'react-router';
import { WorkspaceView } from 'officerdev';
import { useIsMobile } from 'hooks/useIsMobile';
import { useDashboardState } from 'state/useDashboardState';
import { defaultLayout } from './defaultLayout';

export const DashboardsScreen = () => {
  const workspace = useDashboardState<LayoutNode>('screens/dashboards', defaultLayout);
  const isMobile = useIsMobile();
  // Selection lives in the URL (?selected=<id>); on mobile it drives which panel is shown.
  const [searchParams, setSearchParams] = useSearchParams();
  const selected = searchParams.get('selected');
  const mobilePanelId = isMobile && selected ? 'ws-home-right' : undefined;

  return (
    <div className="h-full w-full">
      <WorkspaceView
        workspace={workspace}
        locked
        appTypes={{ allowed: ['dashboard-list', 'dashboard-preview'], fallback: 'dashboard-preview' }}
        mobilePanelId={mobilePanelId}
        onMobilePanelChange={(id) => {
          if (!id)
            setSearchParams(
              (p) => {
                p.delete('selected');
                return p;
              },
              { replace: true },
            );
        }}
      />
    </div>
  );
};
