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

export const ProjectScreen = () => {
  const { id } = useParams<{ id: string }>();
  const { value: projects, isLoaded } = useDashboardState<ProjectDefinition[]>('projects', []);
  const project = projects.find((p) => p.id === id);

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

  return <ProjectScreenInner project={project} />;
};

const ProjectScreenInner = ({ project }: { project: ProjectDefinition }) => {
  const workspace = useDashboardState<LayoutNode>(`proj-layout-${project.id}`, createDefaultLayout());

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