"use client";
import React from "react";
import { CardItem } from "./CardItem";
import { CardSkeleton } from "./CardSkeleton";
import { getFieldValue, getGridClasses } from "./utils";
import { CardDisplayProps } from "./schema";
import { GridSize } from "../HeaderSelections/GridSelectionComponent";

export function CardDisplay<T>({
  showFields,
  data,
  lang,
  translations,
  error,
  loading,
  titleField,
  onCardClick,
  renderCustomField,
  gridCols = 4,
  showViewIcon = false,
  showUpdateIcon = false,
  onViewClick,
  onUpdateClick,
  size = "lg",
}: CardDisplayProps<T>) {
  if (error) {
    return (
      <div className="p-6 text-center text-red-500">
        {error.message || "An error occurred while fetching data."}
      </div>
    );
  }

  return (
    <div className={getGridClasses(gridCols as GridSize)}>
      {loading ? (
        // Loading skeletons
        Array.from({ length: 10 }).map((_, index) => (
          <CardSkeleton
            key={`loading-${index}`}
            index={index}
            showFields={showFields}
            showViewIcon={showViewIcon}
            showUpdateIcon={showUpdateIcon}
          />
        ))
      ) : data.length === 0 ? (
        <div className="col-span-full text-center py-1">
          {translations[lang].noData || "No data found"}
        </div>
      ) : (
        data.map((item: T, index: number) => (
          <CardItem
            key={index}
            item={item}
            index={index}
            showFields={showFields}
            titleField={titleField}
            lang={lang}
            translations={translations}
            showViewIcon={showViewIcon}
            showUpdateIcon={showUpdateIcon}
            onCardClick={onCardClick}
            renderCustomField={renderCustomField}
            onViewClick={onViewClick}
            onUpdateClick={onUpdateClick}
            getFieldValue={getFieldValue}
            size={size}
          />
        ))
      )}
    </div>
  );
}
