import { useParams, Navigate } from 'react-router';
import { useDashboardState } from 'state/useDashboardState';
import type { LayoutNode, DashboardDefinition } from 'officerdev';
import { WorkspaceView, createDefaultLayout } from 'officerdev';

export const DashboardScreen = () => {
  const { id } = useParams<{ id: string }>();
  const { value: dashboards, isLoaded } = useDashboardState<DashboardDefinition[]>('workspaces', []);
  const ws = dashboards.find((w) => w.id === id);

  if (!isLoaded) return null;
  if (!ws) return <Navigate to="/dashboards" replace />;

  return <DashboardScreenInner dashboard={ws} />;
};

const DashboardScreenInner = ({ dashboard }: { dashboard: DashboardDefinition }) => {
  const wsState = useDashboardState<LayoutNode>(`ws-layout-${dashboard.id}`, createDefaultLayout());

  return (
    <div className="h-full w-full">
      <WorkspaceView workspace={wsState} cwd={dashboard.cwd} root={dashboard.root} />
    </div>
  );
};
