import clsx from "clsx"
import type { JSX } from "react"
import type { TableRowSelectionProps } from "./DataTable.types"

export const TableRowSelection = ({
  selectedCount,
  totalCount,
  onSelectAll,
  onClearSelection,
  actions = [],
  className,
}: TableRowSelectionProps): JSX.Element | null => {
  if (selectedCount === 0) return null

  return (
    <div className={clsx("flex items-center justify-between bg-muted/50 px-2 py-1.5", className)}>
      <div className="flex items-center space-x-2">
        <span className="text-sm text-muted-foreground">
          {selectedCount} of {totalCount} row(s) selected.
        </span>
        {onSelectAll && selectedCount < totalCount && (
          <button
            type="button"
            onClick={onSelectAll}
            className="text-sm text-primary underline-offset-4 hover:underline"
          >
            Select all
          </button>
        )}
        {onClearSelection && (
          <button
            type="button"
            onClick={onClearSelection}
            className="text-sm text-muted-foreground underline-offset-4 hover:underline"
          >
            Clear selection
          </button>
        )}
      </div>

      {actions.length > 0 && (
        <div className="flex items-center space-x-2">
          {actions.map(action => (
            <button
              key={action.label}
              type="button"
              onClick={action.onClick}
              disabled={action.disabled}
              className={clsx(
                "inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
                {
                  "bg-primary text-primary-foreground hover:bg-primary/90":
                    action.variant === "default" || !action.variant,
                  "bg-destructive text-destructive-foreground hover:bg-destructive/90":
                    action.variant === "destructive",
                  "border border-input bg-background hover:bg-accent hover:text-accent-foreground":
                    action.variant === "outline",
                  "bg-secondary text-secondary-foreground hover:bg-secondary/80":
                    action.variant === "secondary",
                  "hover:bg-accent hover:text-accent-foreground": action.variant === "ghost",
                  "text-primary underline-offset-4 hover:underline": action.variant === "link",
                },
                "h-8 px-3",
              )}
            >
              {action.label}
            </button>
          ))}
        </div>
      )}
    </div>
  )
}
