import React from 'react';
import { Box, Divider } from '@mui/material';
import { WidgetCard } from './WidgetCard';
import { ItemListSkeleton } from './SkeletonPresets';
import type { SxProps, Theme } from '@mui/material/styles';

export interface ListCardProps<T> {
  title: string;
  icon?: React.ReactNode;
  action?: React.ReactNode;
  items: T[];
  renderItem: (item: T, index: number) => React.ReactNode;
  isLoading?: boolean;
  skeletonCount?: number;
  skeletonItem?: React.ReactNode;
  emptyMessage?: string;
  maxItems?: number;
  footer?: React.ReactNode;
  onClick?: () => void;
  sx?: SxProps<Theme>;
}

/** Card with a list of items, built on WidgetCard. */
export function ListCard<T>({
  title,
  icon,
  action,
  items,
  renderItem,
  isLoading = false,
  skeletonCount = 5,
  skeletonItem,
  emptyMessage = 'Keine Einträge',
  maxItems,
  footer,
  onClick,
  sx,
}: ListCardProps<T>) {
  const displayItems = maxItems ? items.slice(0, maxItems) : items;

  const skeletonContent = skeletonItem ? (
    <Box>
      {Array.from({ length: skeletonCount }, (_, i) => (
        <Box key={i} sx={{ py: 1 }}>
          {skeletonItem}
          {i < skeletonCount - 1 && <Divider sx={{ mt: 1 }} />}
        </Box>
      ))}
    </Box>
  ) : (
    <ItemListSkeleton count={skeletonCount} />
  );

  return (
    <WidgetCard
      title={title}
      icon={icon}
      action={action}
      isLoading={isLoading}
      skeleton={skeletonContent}
      isEmpty={!isLoading && displayItems.length === 0}
      emptyMessage={emptyMessage}
      footer={footer}
      onClick={onClick}
      sx={sx}
    >
      {displayItems.map((item, index) => (
        <React.Fragment key={index}>
          <Box sx={{ py: 1 }}>
            {renderItem(item, index)}
          </Box>
          {index < displayItems.length - 1 && <Divider />}
        </React.Fragment>
      ))}
    </WidgetCard>
  );
}
