import { Empty, Flex } from 'antd';
import { useEffect, useState } from 'react';
import { MarkdownPreviewCard } from './MarkdownPreviewCard';
import type { MarkdownDocument } from './markdown-document';
import type { MarkdownDocumentEntry } from './registry';
import { resolveMarkdownDocuments } from './registry';

export type MarkdownPreviewListProps = {
  entries: MarkdownDocumentEntry[];
  basePath?: string;
  documents?: MarkdownDocument[];
  emptyDescription?: string;
};

export function MarkdownPreviewList({
  entries,
  basePath,
  documents,
  emptyDescription = '표시할 markdown 문서가 없습니다.',
}: MarkdownPreviewListProps) {
  const [resolvedDocuments, setResolvedDocuments] = useState<MarkdownDocument[]>(documents ?? []);

  useEffect(() => {
    if (documents) {
      setResolvedDocuments(documents);
      return;
    }

    let mounted = true;

    void resolveMarkdownDocuments(entries, basePath).then((loadedDocuments) => {
      if (mounted) {
        setResolvedDocuments(loadedDocuments);
      }
    });

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

  if (resolvedDocuments.length === 0) {
    return <Empty description={emptyDescription} />;
  }

  return (
    <Flex vertical gap={16} className="feature-markdown-list">
      {resolvedDocuments.map((document) => (
        <div key={document.id} className="feature-markdown-list__item">
          <MarkdownPreviewCard document={document} />
        </div>
      ))}
    </Flex>
  );
}
