import { Checkbox, DropdownMenu, SvgUse } from "@ivtui/base"
import clsx from "clsx"
import type * as React from "react"
import type { JSX } from "react"
import { useEffect, useRef } from "react"

function Table({ className, ...props }: React.ComponentProps<"table">): JSX.Element {
  return (
    <div className="relative w-full overflow-auto">
      <table
        data-slot="table"
        className={clsx("w-full caption-bottom text-sm", className)}
        {...props}
      />
    </div>
  )
}

function TableHeader({ className, ...props }: React.ComponentProps<"thead">): JSX.Element {
  return (
    <thead data-slot="table-header" className={clsx("[&_tr]:border-b", className)} {...props} />
  )
}

function TableBody({ className, ...props }: React.ComponentProps<"tbody">): JSX.Element {
  return (
    <tbody
      data-slot="table-body"
      className={clsx("[&_tr:last-child]:border-0", className)}
      {...props}
    />
  )
}

function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">): JSX.Element {
  return (
    <tfoot
      data-slot="table-footer"
      className={clsx("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0", className)}
      {...props}
    />
  )
}

function TableRow({ className, ...props }: React.ComponentProps<"tr">): JSX.Element {
  return (
    <tr
      data-slot="table-row"
      className={clsx(
        "border-b transition-colors hover:bg-[#0040FF08] data-[state=selected]:bg-[#0040FF08]",
        className,
      )}
      {...props}
    />
  )
}

function TableHead({ className, ...props }: React.ComponentProps<"th">): JSX.Element {
  return (
    <th
      data-slot="table-head"
      className={clsx(
        "h-12 px-4 text-left align-middle font-medium [&:has([role=checkbox])]:pr-0",
        className,
      )}
      {...props}
    />
  )
}

function TableCell({ className, ...props }: React.ComponentProps<"td">): JSX.Element {
  return (
    <td
      data-slot="table-cell"
      className={clsx("p-4 align-middle [&:has([role=checkbox])]:pr-0", className)}
      {...props}
    />
  )
}

function TableCaption({ className, ...props }: React.ComponentProps<"caption">): JSX.Element {
  return (
    <caption
      data-slot="table-caption"
      className={clsx("mt-4 text-sm text-muted-foreground", className)}
      {...props}
    />
  )
}

function SortableHeader({
  children,
  isSorted,
  isSortedDesc,
  onSort,
  onHide,
  className,
  ...props
}: {
  children: React.ReactNode
  isSorted: boolean
  isSortedDesc: boolean
  onSort?: (direction: "asc" | "desc") => void
  onHide?: () => void
  className?: string
} & React.ComponentProps<"th">): JSX.Element {
  const handleSort = (direction: "asc" | "desc") => {
    onSort?.(direction)
  }

  const renderSortIcon = () => {
    if (isSorted) {
      if (isSortedDesc) {
        return <SvgUse icon="arrow-downward" className="size-4" />
      }
      return <SvgUse icon="arrow-upward" className="size-4" />
    }
    return <SvgUse icon="sort-vertical-outline" className="size-5" />
  }

  return (
    <TableHead className={clsx("select-none", className)} {...props}>
      <div className="flex items-center justify-between">
        <span className="flex-1">{children}</span>
        <DropdownMenu.Root>
          <DropdownMenu.Trigger>
            <button
              type="button"
              className="ml-2 size-4 rounded-sm opacity-70 ring-offset-background transition-colors hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
              onClick={e => e.stopPropagation()}
            >
              {renderSortIcon()}
              <span className="sr-only">Toggle sort</span>
            </button>
          </DropdownMenu.Trigger>
          <DropdownMenu.Content align="end">
            <DropdownMenu.Item onClick={() => handleSort("asc")}>
              <SvgUse icon="arrow-upward" className="inline size-4" />
              <span className="ml-2">Asc</span>
            </DropdownMenu.Item>
            <DropdownMenu.Item onClick={() => handleSort("desc")}>
              <SvgUse icon="arrow-downward" className="inline size-4" />
              <span className="ml-2">Desc</span>
            </DropdownMenu.Item>
            <DropdownMenu.Separator />
            <DropdownMenu.Item onClick={onHide}>
              <SvgUse icon="eyes-off-outline" className="mr-2 size-4" />
              Hide
            </DropdownMenu.Item>
          </DropdownMenu.Content>
        </DropdownMenu.Root>
      </div>
    </TableHead>
  )
}

// Custom checkbox component that supports indeterminate state
function TableCheckbox({
  indeterminate = false,
  ...props
}: React.ComponentProps<typeof Checkbox> & { indeterminate?: boolean }): JSX.Element {
  const ref = useRef<HTMLButtonElement>(null)

  useEffect(() => {
    if (ref.current) {
      // Cast to HTMLInputElement to access the indeterminate property
      ;(ref.current as unknown as HTMLInputElement).indeterminate = indeterminate
    }
  }, [indeterminate])

  return <Checkbox ref={ref} {...props} />
}

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