import { motion } from 'framer-motion';
import type { ComponentProps } from 'react';
import { cn } from '@/lib/utils';

function Table({ className, ref, ...props }: ComponentProps<'table'>) {
  return (
    <div className="relative w-full overflow-auto">
      <table
        ref={ref}
        className={cn('w-full caption-bottom text-sm', 'border-collapse', className)}
        {...props}
      />
    </div>
  );
}

function TableHeader({ className, ref, ...props }: ComponentProps<'thead'>) {
  return (
    <thead
      ref={ref}
      className={cn('[&_tr]:border-b [&_tr]:border-border/60', className)}
      {...props}
    />
  );
}

function TableBody({ className, ref, ...props }: ComponentProps<'tbody'>) {
  return <tbody ref={ref} className={cn('[&_tr:last-child]:border-0', className)} {...props} />;
}

function TableFooter({ className, ref, ...props }: ComponentProps<'tfoot'>) {
  return (
    <tfoot
      ref={ref}
      className={cn(
        'border-t border-border/60 bg-muted/50 font-medium',
        '[&>tr]:last:border-b-0',
        className,
      )}
      {...props}
    />
  );
}

function TableRow({ className, ref, ...props }: ComponentProps<typeof motion.tr>) {
  return (
    <motion.tr
      ref={ref}
      className={cn(
        'border-b border-border/50 last:border-0',
        'transition-colors duration-150',
        'hover:bg-accent/50',
        'data-[state=selected]:bg-accent/70',
        className,
      )}
      {...props}
    />
  );
}

function TableHead({ className, ref, ...props }: ComponentProps<'th'>) {
  return (
    <th
      ref={ref}
      className={cn(
        'h-10 px-4 text-left align-middle',
        'text-xs font-semibold uppercase tracking-normal',
        'text-muted-foreground',
        '[&:has([role=checkbox])]:pr-0',
        '[&>[role=checkbox]]:translate-y-[2px]',
        className,
      )}
      {...props}
    />
  );
}

function TableCell({ className, ref, ...props }: ComponentProps<'td'>) {
  return (
    <td
      ref={ref}
      className={cn(
        'px-5 py-3 align-middle',
        'text-sm font-medium text-foreground',
        '[&:has([role=checkbox])]:pr-0',
        '[&>[role=checkbox]]:translate-y-[2px]',
        className,
      )}
      {...props}
    />
  );
}

function TableCaption({ className, ref, ...props }: ComponentProps<'caption'>) {
  return (
    <caption ref={ref} className={cn('mt-4 text-sm text-muted-foreground', className)} {...props} />
  );
}

export { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCaption };
