import type { ReactNode } from 'react';
import Link from 'next/link';
import { buttonVariants } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow
} from '@/components/ui/table';
import { cn } from '@/lib/utils';

type Column<T> = {
  key: string;
  header: string;
  cell: (row: T) => ReactNode;
  className?: string;
};

type ExportLink = {
  label: string;
  href: string;
};

export function ReportTableCard<T>({
  title,
  description,
  exportLinks,
  columns,
  rows,
  emptyMessage
}: {
  title: string;
  description: string;
  exportLinks: ExportLink[];
  columns: Column<T>[];
  rows: T[];
  emptyMessage: string;
}) {
  return (
    <Card className='overflow-hidden'>
      <CardHeader className='flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between'>
        <div className='min-w-0 space-y-1'>
          <CardTitle>{title}</CardTitle>
          <CardDescription>{description}</CardDescription>
        </div>

        <div className='flex flex-col gap-2 sm:flex-row'>
          {exportLinks.map((link) => (
            <Link
              key={`${title}-${link.label}`}
              href={link.href}
              className={cn(
                buttonVariants({ variant: 'outline', size: 'sm' }),
                'w-full sm:w-auto'
              )}
            >
              ส่งออก {link.label}
            </Link>
          ))}
        </div>
      </CardHeader>

      <CardContent className='min-w-0'>
        {rows.length === 0 ? (
          <div className='text-muted-foreground rounded-md border border-dashed px-4 py-8 text-sm'>
            {emptyMessage}
          </div>
        ) : (
          <div className='w-full overflow-x-auto'>
            <Table className='min-w-full'>
              <TableHeader>
                <TableRow>
                  {columns.map((column) => (
                    <TableHead key={column.key} className={column.className}>
                      {column.header}
                    </TableHead>
                  ))}
                </TableRow>
              </TableHeader>
              <TableBody>
                {rows.map((row, rowIndex) => (
                  <TableRow key={rowIndex}>
                    {columns.map((column) => (
                      <TableCell key={column.key} className={column.className}>
                        {column.cell(row)}
                      </TableCell>
                    ))}
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
        )}
      </CardContent>
    </Card>
  );
}
