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 './constants';

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

  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);
        }
      })
      .catch(() => {
        if (mounted) {
          setSavedLayouts([]);
        }
      });

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

  const docFolders = useMemo(
    () =>
      Array.from(new Set(docsDocuments.map((document) => document.folder))).sort((left, right) => {
        if (left === DOCS_DEFAULT_FOLDER) {
          return -1;
        }

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

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

  return {
    componentSamples,
    widgetSamples,
    docsDocuments,
    savedLayouts,
    setSavedLayouts,
    docFolders,
  };
}
