import {
  ArrowDownIcon,
  ArrowUpIcon,
  CaretSortIcon,
  EyeNoneIcon,
} from "@radix-ui/react-icons"
import type { Column } from "@tanstack/react-table"
import { Button } from "@/components/ui/button"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { cn } from "@/lib/utils"

interface DataTableColumnHeaderProps<TData, TValue>
  extends React.HTMLAttributes<HTMLDivElement> {
  column: Column<TData, TValue>
  title: string
  icon?: React.ReactNode
  buttonClassName?: string
}

export function DataTableColumnHeader<TData, TValue>({
  column,
  title,
  className,
  icon,
  buttonClassName,
  ...props
}: DataTableColumnHeaderProps<TData, TValue>) {
  const resolvedClassName = cn("text-xs", className)

  if (!column.getCanSort()) {
    return (
      <div className={resolvedClassName} {...props}>
        {title}
      </div>
    )
  }

  const resolvedButtonClassName =
    buttonClassName ?? "-ml-3 h-8 data-[state=open]:bg-accent"

  return (
    <div
      className={cn("flex items-center space-x-2", resolvedClassName)}
      {...props}
    >
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button
            variant="ghost"
            size="sm"
            className={cn(resolvedButtonClassName)}
          >
            {icon}
            <span>{title}</span>
            {column.getIsSorted() === "desc" ? (
              <ArrowDownIcon className="ml-2 size-4" />
            ) : column.getIsSorted() === "asc" ? (
              <ArrowUpIcon className="ml-2 size-4" />
            ) : (
              <CaretSortIcon className="ml-2 size-4" />
            )}
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="start">
          <DropdownMenuItem
            onClick={() => column.toggleSorting(false)}
            className="text-xs"
          >
            <ArrowUpIcon className="mr-2 size-3.5 text-muted-foreground/70" />
            Ascending
          </DropdownMenuItem>
          <DropdownMenuItem
            onClick={() => column.toggleSorting(true)}
            className="text-xs"
          >
            <ArrowDownIcon className="mr-2 size-3.5 text-muted-foreground/70" />
            Descending
          </DropdownMenuItem>
          <DropdownMenuSeparator />
          <DropdownMenuItem
            onClick={() => column.toggleVisibility(false)}
            className="text-xs"
            disabled={!column.getCanHide()}
          >
            <EyeNoneIcon className="mr-2 size-3.5 text-muted-foreground/70" />
            Hide
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
    </div>
  )
}
