import {
  Badge,
  Button,
  Checkbox,
  IconButton,
  Input,
  InputAdornment,
  InputAdornmentButton,
  InputControl,
  InputRoot,
  Popover,
  Separator,
  SvgUse,
} from "@ivtui/base"
import clsx from "clsx"
import type { JSX } from "react"
import { useState } from "react"
import type { TableToolbarProps } from "./DataTable.types"

export const TableToolbar = ({
  searchValue = "",
  onSearchChange,
  searchPlaceholder = "Search...",
  filters = [],
  className,
  columns = [],
}: Readonly<TableToolbarProps>): JSX.Element => {
  const [openPopover, setOpenPopover] = useState<string | null>(null)
  const [viewPopoverOpen, setViewPopoverOpen] = useState(false)

  const handleFilterChange = (
    key: string,
    value: string,
    onValueChange?: (value: string[]) => void,
  ) => {
    const current = filters.find(f => f.key === key)?.value ?? []
    const newValue = current.includes(value)
      ? current.filter(v => v !== value)
      : [...current, value]
    onValueChange?.(newValue)
  }

  // Determine if reset should be shown
  const hasActiveFilters = filters.some(f => f.value && f.value.length > 0)
  const showReset = !!searchValue || hasActiveFilters

  return (
    <div className={clsx("flex items-center justify-between", className)}>
      <div className="flex flex-1 items-center gap-2">
        {/* Search Input */}
        {onSearchChange && (
          <InputRoot className="w-72">
            <InputAdornment>
              <SvgUse icon="search" />
            </InputAdornment>
            <InputControl>
              <Input
                placeholder={searchPlaceholder}
                value={searchValue}
                onChange={e => onSearchChange(e.target.value)}
              />
            </InputControl>
            {searchValue && (
              <InputAdornment>
                <InputAdornmentButton
                  type="button"
                  onClick={() => onSearchChange("")}
                  aria-label="Clear search"
                >
                  <SvgUse icon="close-outline" />
                </InputAdornmentButton>
              </InputAdornment>
            )}
          </InputRoot>
        )}

        {/* Filters */}
        {filters.map(filter => {
          const selected = filter.value ?? []
          return (
            <Popover.Root
              key={filter.key}
              open={openPopover === filter.key}
              onOpenChange={(open: boolean) => setOpenPopover(open ? filter.key : null)}
            >
              <Popover.Trigger>
                <Button
                  variant="outline"
                  size="2"
                  color="gray"
                  className={clsx(
                    "h-8 border-dashed flex items-center gap-2",
                    selected.length > 0 && "bg-accent text-accent-foreground",
                  )}
                >
                  <SvgUse icon="add-circle-outline" className="size-4" />
                  {filter.label}
                  {selected.length > 0 && (
                    <>
                      <Separator orientation="vertical" className="mx-2 h-4" />
                      {/* Mobile: just a count */}
                      <Badge variant="soft" className="rounded-sm px-1 font-normal lg:hidden">
                        {selected.length}
                      </Badge>
                      {/* Desktop: show count or individual badges */}
                      <div className="hidden space-x-1 lg:flex">
                        {selected.length > 2 ? (
                          <Badge variant="soft" className="rounded-sm px-1 font-normal">
                            {selected.length} selected
                          </Badge>
                        ) : (
                          filter.options
                            .filter(option => selected.includes(option.value))
                            .map(option => (
                              <Badge
                                variant="soft"
                                key={option.value}
                                className="rounded-sm px-1 font-normal"
                              >
                                {option.label}
                              </Badge>
                            ))
                        )}
                      </div>
                    </>
                  )}
                </Button>
              </Popover.Trigger>
              <Popover.Content
                sideOffset={8}
                className="z-50 !w-fit rounded-md border bg-popover p-4 text-popover-foreground shadow-md"
              >
                <div className="mb-2 font-medium text-sm">{filter.label}</div>
                <div className="max-h-40 overflow-y-auto mb-2">
                  {filter.options.length === 0 && (
                    <div className="text-sm text-muted-foreground py-2 text-center">No options</div>
                  )}
                  {filter.options.map(option => (
                    <label
                      key={option.value}
                      htmlFor={`filter-${filter.key}-${option.value}`}
                      className="flex items-center gap-2 py-1 cursor-pointer"
                    >
                      <Checkbox
                        id={`filter-${filter.key}-${option.value}`}
                        checked={selected.includes(option.value)}
                        onCheckedChange={() =>
                          handleFilterChange(filter.key, option.value, filter.onValueChange)
                        }
                      />
                      <span className="text-sm">{option.label}</span>
                    </label>
                  ))}
                </div>
              </Popover.Content>
            </Popover.Root>
          )
        })}

        {/* Reset Button */}
        {showReset && (
          <IconButton
            variant="outline"
            size="2"
            color="gray"
            className="flex items-center gap-2 border-dashed"
            onClick={() => {
              onSearchChange?.("")
              for (const f of filters) {
                f.onValueChange?.([])
              }
            }}
          >
            <SvgUse icon="reload" className="size-4" />
          </IconButton>
        )}
      </div>
      {/* View (column visibility) button */}
      {columns.length > 0 && (
        <div className="flex items-center">
          <Popover.Root open={viewPopoverOpen} onOpenChange={setViewPopoverOpen}>
            <Popover.Trigger>
              <Button
                variant="outline"
                size="2"
                color="gray"
                className="flex items-center gap-2"
                aria-label="View columns"
              >
                <SvgUse icon="light-event-list-outline" className="size-4" />
                View
              </Button>
            </Popover.Trigger>
            <Popover.Content
              sideOffset={8}
              className="z-50 !w-fit rounded-md border bg-popover p-4 text-popover-foreground shadow-md"
            >
              <div className="mb-2 font-medium text-sm">Toggle columns</div>
              <div className="max-h-40 overflow-y-auto mb-2 flex flex-col gap-1">
                {columns.map(col => (
                  <label
                    key={col.id}
                    htmlFor={`column-${col.id}`}
                    className="flex items-center gap-2 py-1 cursor-pointer"
                  >
                    <Checkbox
                      id={`column-${col.id}`}
                      checked={col.visible}
                      onCheckedChange={col.toggle}
                      disabled={col.canHide === false}
                    />
                    <span className="text-sm">{col.label}</span>
                  </label>
                ))}
              </div>
            </Popover.Content>
          </Popover.Root>
        </div>
      )}
    </div>
  )
}
