import { Empty, Flex } from 'antd';
import { createElement, useEffect, useState } from 'react';
import type { LoadedSampleEntry, SampleEntry } from '../../../samples/registry';
import { resolveSampleEntries } from '../../../samples/registry';

export type SampleWidgetsLayoutProps = {
  entries: SampleEntry[];
  pathFilter?: string;
  includeComponentIds?: string[];
  includeSampleIds?: string[];
  disableWidgetCardWrapper?: boolean;
  singlePreviewMode?: boolean;
};

export function SampleWidgetsLayout({
  entries,
  pathFilter = '/widgets/',
  includeComponentIds = [],
  includeSampleIds = [],
  disableWidgetCardWrapper = false,
  singlePreviewMode = false,
}: SampleWidgetsLayoutProps) {
  const [sampleEntries, setSampleEntries] = useState<LoadedSampleEntry[]>([]);

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

    void resolveSampleEntries(entries, pathFilter).then((loadedEntries) => {
      if (mounted) {
        setSampleEntries(loadedEntries);
      }
    });

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

  const visibleEntries = sampleEntries.filter((entry) => {
    if (includeComponentIds.length > 0 && !includeComponentIds.includes(entry.sampleMeta.componentId)) {
      return false;
    }

    if (includeSampleIds.length > 0 && !includeSampleIds.includes(entry.sampleMeta.id)) {
      return false;
    }

    return true;
  });

  if (visibleEntries.length === 0) {
    return <Empty description="표시할 위젯 샘플이 없습니다." />;
  }

  return (
    <Flex
      gap={singlePreviewMode ? 0 : 20}
      wrap={!singlePreviewMode}
      className={`sample-widgets-layout${singlePreviewMode ? ' sample-widgets-layout--single-preview' : ''}`}
    >
      {visibleEntries.map(({ modulePath, Sample, sampleMeta }) => (
        <div
          key={modulePath}
          id={`widget-sample-${sampleMeta.componentId}`}
          className={`sample-widgets-layout__item${singlePreviewMode ? ' sample-widgets-layout__item--single-preview' : ''}`}
          data-focus-id={`widget:${sampleMeta.componentId}`}
        >
          <div className={`sample-widgets-layout__item${singlePreviewMode ? ' sample-widgets-layout__item--single-preview' : ''}`}>
            {createElement(Sample, { disableWidgetCardWrapper })}
          </div>
        </div>
      ))}
    </Flex>
  );
}
