import { Card, Empty, Flex, Typography } from 'antd';
import { useEffect, useMemo, useState } from 'react';
import { docsMarkdownEntries } from '../../../app/manifests/docs.manifest';
import { FolderTreeNav } from '../../../components/navigation';
import {
  MarkdownPreviewCard,
  resolveMarkdownDocuments,
  type MarkdownDocument,
} from '../../../components/markdownPreview';

const { Text } = Typography;

export function DocsMarkdownPreviewLayout() {
  const [documents, setDocuments] = useState<MarkdownDocument[]>([]);

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

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

    return () => {
      mounted = false;
    };
  }, []);
  const grouped = useMemo(() => {
    const folderMap = new Map<string, typeof documents>();

    documents.forEach((document) => {
      const bucket = folderMap.get(document.folder) ?? [];
      bucket.push(document);
      folderMap.set(document.folder, bucket);
    });

    return Array.from(folderMap.entries()).sort((left, right) => left[0].localeCompare(right[0]));
  }, [documents]);

  if (documents.length === 0) {
    return <Empty description="표시할 docs markdown 문서가 없습니다." />;
  }

  return (
    <div className="docs-markdown-layout">
      <aside className="docs-markdown-layout__sidebar">
        <Card title="Docs Folders" className="component-samples-layout__nav-card">
          <FolderTreeNav
            title="Docs Tree"
            groups={grouped.map(([folder, folderDocuments]) => ({
              id: `docs-folder-${folder}`,
              label: folder,
              items: folderDocuments.map((document) => ({
                id: document.id,
                label: document.title,
                href: `#doc-item-${document.id}`,
              })),
            }))}
          />
        </Card>
      </aside>

      <div className="docs-markdown-layout__content">
        <Flex vertical gap={20}>
          {grouped.map(([folder, folderDocuments]) => (
            <section key={folder} id={`docs-folder-${folder}`}>
              <Card title={folder} extra={<Text code>{folderDocuments.length} docs</Text>}>
                <Flex vertical gap={16}>
                  {folderDocuments.map((document) => (
                    <div
                      key={document.id}
                      id={`doc-item-${document.id}`}
                      className="feature-markdown-list__item"
                    >
                      <MarkdownPreviewCard document={document} />
                    </div>
                  ))}
                </Flex>
              </Card>
            </section>
          ))}
        </Flex>
      </div>
    </div>
  );
}
