import { useEffect, useMemo, useState } from 'react';
import { resolveMarkdownDocuments } from '../../../components/markdownPreview';
import { resolveSampleEntries, type LoadedSampleEntry } from '../../../samples/registry';
import { listSavedLayouts, type SavedLayoutRecord } from '../../../views/play/layoutStorage';
import { docsMarkdownEntries } from '../../manifests/docs.manifest';
import { componentSampleEntries, widgetSampleEntries } from '../../manifests/samples.manifest';
import { DOCS_DEFAULT_FOLDER } from '../routes';

const DOCS_FOLDER_ORDER = ['project'] as const;

export function useMainLayoutData() {
  const [componentSamples, setComponentSamples] = useState<LoadedSampleEntry[]>([]);
  const [widgetSamples, setWidgetSamples] = useState<LoadedSampleEntry[]>([]);
  const [docsDocuments, setDocsDocuments] = useState<Awaited<ReturnType<typeof resolveMarkdownDocuments>>>([]);
  const [savedLayouts, setSavedLayouts] = useState<SavedLayoutRecord[]>([]);
  const [savedLayoutsReady, setSavedLayoutsReady] = useState(false);

  useEffect(() => {
    let mounted = true;

    void resolveMarkdownDocuments(docsMarkdownEntries, '/docs/').then((documents) => {
      if (mounted) {
        setDocsDocuments(documents);
      }
    });

    void resolveSampleEntries(componentSampleEntries, '/components/').then((loadedEntries) => {
      if (mounted) {
        setComponentSamples(loadedEntries);
      }
    });

    void resolveSampleEntries(widgetSampleEntries, '/widgets/').then((loadedEntries) => {
      if (mounted) {
        setWidgetSamples(loadedEntries);
      }
    });

    return () => {
      mounted = false;
    };
  }, []);

  useEffect(() => {
    let mounted = true;

    void listSavedLayouts()
      .then((layouts) => {
        if (mounted) {
          setSavedLayouts(layouts);
          setSavedLayoutsReady(true);
        }
      })
      .catch(() => {
        if (mounted) {
          setSavedLayouts([]);
          setSavedLayoutsReady(true);
        }
      });

    return () => {
      mounted = false;
    };
  }, []);

  const docFolders = useMemo(
    () =>
      Array.from(new Set(docsDocuments.map((document) => document.folder))).sort((left, right) => {
        const leftIndex = DOCS_FOLDER_ORDER.indexOf(left as (typeof DOCS_FOLDER_ORDER)[number]);
        const rightIndex = DOCS_FOLDER_ORDER.indexOf(right as (typeof DOCS_FOLDER_ORDER)[number]);

        if (leftIndex >= 0 || rightIndex >= 0) {
          if (leftIndex < 0) {
            return 1;
          }

          if (rightIndex < 0) {
            return -1;
          }

          return leftIndex - rightIndex;
        }

        if (left === DOCS_DEFAULT_FOLDER) {
          return -1;
        }

        if (right === DOCS_DEFAULT_FOLDER) {
          return 1;
        }

        return left.localeCompare(right);
      }),
    [docsDocuments],
  );

  return {
    componentSampleEntries,
    widgetSampleEntries,
    componentSamples,
    widgetSamples,
    docsDocuments,
    savedLayouts,
    savedLayoutsReady,
    setSavedLayouts,
    docFolders,
  };
}
