'use client';

import dynamic from 'next/dynamic';
import { useEffect, useRef, useState } from 'react';

import { DocumentationViewer, SplitterLayout } from '@5minds/processcube_app_sdk/client';
import '@5minds/processcube_app_sdk/client/components/DiagramDocumentationInspector.css';

import type { getDiagramsPaths } from '../utils/getDiagrams';
import ProcessModelList from './processModelList';

const DEFAULT_SPLITTER_SIZE = 55;

export function ProcessOverview(props: {
  diagramsPaths: Awaited<ReturnType<typeof getDiagramsPaths>>;
  readme: string;
}) {
  const splitterRef = useRef<SplitterLayout>(null);
  const [splitterSize, setSplitterSize] = useState(DEFAULT_SPLITTER_SIZE);

  useEffect(() => {
    if (!window) {
      return;
    }

    // Not using the useSearchParams hook, because the component should be able to run in non-Next.js environments
    const searchParams = new URLSearchParams(window.location.search);

    if (!searchParams.has('splitterSize')) {
      return;
    }

    const splitterSize = parseFloat(searchParams.get('splitterSize')!);
    if (isNaN(splitterSize) || splitterSize === DEFAULT_SPLITTER_SIZE) {
      return;
    }

    setSplitterSize(splitterSize);
  }, []);

  useEffect(() => {
    const searchParams = new URLSearchParams(window.location.search);

    if (splitterSize !== DEFAULT_SPLITTER_SIZE) {
      searchParams.set('splitterSize', splitterSize.toString());
    } else {
      searchParams.delete('splitterSize');
    }

    splitterRef.current?.setSecondaryPaneSize(splitterSize);

    const decodedURIHash = decodeURIComponent(window.location.hash.slice(1));
    const headingElement = decodedURIHash.length > 0 ? document.getElementById(decodedURIHash) : null;

    // Not using the useRouter hook, because the component should be able to run in non-Next.js environments
    window.history.replaceState(null, '', `?${searchParams.toString()}${headingElement ? window.location.hash : ''}`);
    window.location.hash && (window.location.hash = window.location.hash); // Seems stupid, but is needed to trigger a hashchange event
    headingElement?.scrollIntoView();
  }, [splitterSize]);

  return (
    <SplitterLayout
      ref={splitterRef}
      vertical
      percentage
      secondaryInitialSize={DEFAULT_SPLITTER_SIZE}
      secondaryDefaultSize={DEFAULT_SPLITTER_SIZE}
      onDragEnd={(_prev: number, current: number) => setSplitterSize(Math.round(current))}
    >
      <div className="flex w-full justify-center p-4">
        <div className="flex w-full max-w-6xl">
          <ProcessModelList diagramsPaths={props.diagramsPaths}></ProcessModelList>
        </div>
      </div>
      <div className="flex justify-center h-full">
        <DocumentationViewer documentation={props.readme} />
      </div>
    </SplitterLayout>
  );
}

export const ProcessOverviewNextJS = dynamic(() => Promise.resolve(ProcessOverview), {
  ssr: false,
});
