"use client";

import { Skeleton } from "@/components/ui/skeleton";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { cn } from "@/lib/utils";
import type { CSSProperties } from "react";

interface DataTableSkeletonProps {

  rows?: number;

  columns?: number;

  showRowNumber?: boolean;

  minWidth?: number | string;

  className?: string;
}

const BODY_CELL_WIDTHS = ["60%", "85%", "45%", "70%", "55%", "78%", "40%", "65%"];

const sizeToCss = (value: number | string): string =>
  typeof value === "number" ? `${value}px` : value;

export function DataTableSkeleton({
  rows = 8,
  columns = 5,
  showRowNumber = true,
  minWidth,
  className,
}: DataTableSkeletonProps) {
  const tableStyle: CSSProperties | undefined =
    minWidth === undefined ? undefined : { minWidth: sizeToCss(minWidth) };

  const headerCells = Array.from({ length: columns });
  const bodyCells = Array.from({ length: columns });
  const bodyRows = Array.from({ length: rows });

  return (
    <div
      role="status"
      aria-busy="true"
      aria-label="Loading"
      className={cn("w-full overflow-x-auto", className)}
    >
      <Table className="border-collapse bg-card" style={tableStyle}>
        <TableHeader>
          <TableRow className="border-b border-border bg-highlights-bg hover:bg-highlights-bg">
            {showRowNumber && (
              <TableHead className="h-12 w-14 px-4 text-center">
                <Skeleton className="mx-auto h-3 w-4" />
              </TableHead>
            )}
            {headerCells.map((_, i) => (
              <TableHead key={i} className="h-12 px-4">
                <Skeleton className="h-3 w-24" />
              </TableHead>
            ))}
          </TableRow>
        </TableHeader>

        <TableBody>
          {bodyRows.map((_, rowIndex) => (
            <TableRow
              key={rowIndex}
              className="h-[72px] border-b border-border bg-card hover:bg-card"
            >
              {showRowNumber && (
                <TableCell className="px-4 text-center">
                  <Skeleton className="mx-auto h-3 w-4" />
                </TableCell>
              )}
              {bodyCells.map((_, cellIndex) => (
                <TableCell key={cellIndex} className="px-4">
                  <Skeleton
                    className="h-4"
                    style={{
                      width:
                        BODY_CELL_WIDTHS[
                          (rowIndex + cellIndex) % BODY_CELL_WIDTHS.length
                        ],
                    }}
                  />
                </TableCell>
              ))}
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </div>
  );
}
