import { useLocation } from 'react-router-dom';
import { SampleWidgetsLayout } from '../../../features/layout/widget-sample-gallery';
import { LayoutDrawPage } from '../../../features/layout/draw';
import { AppsLibraryView } from '../../../views/play/apps/apps/AppsLibraryView';
import { CbtPlayAppView } from '../../../views/play/apps/cbt/CbtPlayAppView';
import { TestPlayAppView } from '../../../views/play/apps/test/TestPlayAppView';
import { LayoutPlaygroundView } from '../../../views/play/LayoutPlaygroundView';
import { useMainLayoutContext } from '../layout/MainLayoutContext';
import { readPreviewTargetDescriptorFromUrl } from '../previewRuntime';
import { resolveSavedLayoutIdFromMenuKey } from '../routes';
import { renderSavedLayoutContent } from '../../../features/layout/renderSavedLayoutContent';

export function PlayPage() {
  const location = useLocation();
  const { selectedPlayMenu, savedLayouts, setSavedLayouts, widgetSampleEntries } = useMainLayoutContext();
  const selectedSavedLayoutId = resolveSavedLayoutIdFromMenuKey(selectedPlayMenu);
  const selectedSavedLayout = selectedSavedLayoutId
    ? savedLayouts.find((layout) => layout.id === selectedSavedLayoutId) ?? null
    : null;
  const previewTarget = readPreviewTargetDescriptorFromUrl();
  const isWidgetPreview = selectedPlayMenu === 'cbt' && previewTarget?.type === 'widget';
  const panelClassName = selectedSavedLayoutId ? 'app-main-panel app-main-panel--play app-main-panel--play-saved' : 'app-main-panel app-main-panel--play';

  return (
    <div className={panelClassName}>
      {isWidgetPreview ? (
        <SampleWidgetsLayout
          key={location.search}
          entries={widgetSampleEntries}
          includeComponentIds={[previewTarget.componentId]}
          includeSampleIds={previewTarget.sampleId ? [previewTarget.sampleId] : []}
          disableWidgetCardWrapper
          singlePreviewMode
        />
      ) : null}
      {selectedPlayMenu === 'layout' ? <LayoutPlaygroundView onSavedLayoutsChange={setSavedLayouts} /> : null}
      {selectedPlayMenu === 'draw' ? <LayoutDrawPage /> : null}
      {selectedPlayMenu === 'apps' ? <AppsLibraryView /> : null}
      {selectedPlayMenu === 'test' ? <TestPlayAppView /> : null}
      {selectedPlayMenu === 'cbt' && !isWidgetPreview ? <CbtPlayAppView /> : null}
      {selectedSavedLayoutId && selectedSavedLayout
        ? renderSavedLayoutContent({
            layoutId: selectedSavedLayoutId,
            layout: selectedSavedLayout,
            savedLayouts,
            onSavedLayoutsChange: setSavedLayouts,
          })
        : null}
    </div>
  );
}
