import { CheckIcon, Cross2Icon } from '@radix-ui/react-icons'

import * as React from 'react'

import { Badge } from '@components/ui/badge/badge'
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
  CommandSeparator,
} from '@components/ui/command/command'
import { DataGridCellWrapper } from '@components/ui/data-grid/data-grid-cell-wrapper'
import { getLineCount } from '@components/ui/data-grid/data-grid-utils'
import { Popover, PopoverAnchor, PopoverContent } from '@components/ui/popover/popover'
import { cn } from '@lib/utils'
import { CellVariantProps } from './cell-variant-types'

export function MultiSelectCell<TData>({
  cell,
  table,
  rowIndex,
  columnId,
  isFocused,
  isEditing,
  isSelected,
}: Readonly<CellVariantProps<TData, string[]>>) {
  const cellValue = React.useMemo(() => cell.getValue() ?? [], [cell])

  const cellId = `${rowIndex}-${columnId}`
  const prevCellIdRef = React.useRef(cellId)

  const [selectedValues, setSelectedValues] = React.useState<string[]>(cellValue)
  const [open, setOpen] = React.useState(false)
  const [searchValue, setSearchValue] = React.useState('')
  const containerRef = React.useRef<HTMLDivElement>(null)
  const inputRef = React.useRef<HTMLInputElement>(null)
  const meta = table.options.meta
  const cellOpts = cell.column.columnDef.meta?.cell
  const options = cellOpts?.variant === 'multi-select' ? cellOpts.options : []
  const sideOffset = -(containerRef.current?.clientHeight ?? 0)

  if (prevCellIdRef.current !== cellId) {
    prevCellIdRef.current = cellId
    setSelectedValues(cellValue)
    setOpen(false)
    setSearchValue('')
  }

  const onValueChange = React.useCallback(
    (value: string) => {
      const newValues = selectedValues.includes(value)
        ? selectedValues.filter((v) => v !== value)
        : [...selectedValues, value]

      setSelectedValues(newValues)
      meta?.onDataUpdate?.({ rowIndex, columnId, value: newValues })
      // Clear search input and focus back on input after selection
      setSearchValue('')
      queueMicrotask(() => inputRef.current?.focus())
    },
    [selectedValues, meta, rowIndex, columnId],
  )

  const removeValue = React.useCallback(
    (valueToRemove: string, event?: React.MouseEvent) => {
      event?.stopPropagation()
      event?.preventDefault()
      const newValues = selectedValues.filter((v) => v !== valueToRemove)
      setSelectedValues(newValues)
      meta?.onDataUpdate?.({ rowIndex, columnId, value: newValues })
      // Focus back on input after removing
      setTimeout(() => inputRef.current?.focus(), 0)
    },
    [selectedValues, meta, rowIndex, columnId],
  )

  const clearAll = React.useCallback(() => {
    setSelectedValues([])
    meta?.onDataUpdate?.({ rowIndex, columnId, value: [] })
    queueMicrotask(() => inputRef.current?.focus())
  }, [meta, rowIndex, columnId])

  const onOpenChange = React.useCallback(
    (isOpen: boolean) => {
      setOpen(isOpen)
      if (!isOpen) {
        setSearchValue('')
        meta?.onCellEditingStop?.()
      }
    },
    [meta],
  )

  const onOpenAutoFocus: NonNullable<React.ComponentProps<typeof PopoverContent>['onOpenAutoFocus']> =
    React.useCallback((event) => {
      event.preventDefault()
      inputRef.current?.focus()
    }, [])

  const onWrapperKeyDown = React.useCallback(
    (event: React.KeyboardEvent<HTMLDivElement>) => {
      if (isEditing) {
        if (event.key === 'Escape') {
          event.preventDefault()
          setSelectedValues(cellValue)
          setSearchValue('')
          setOpen(false)
          meta?.onCellEditingStop?.()
        } else if (event.key === 'Tab') {
          event.preventDefault()
          setSearchValue('')
          setOpen(false)
          meta?.onCellEditingStop?.({
            direction: event.shiftKey ? 'left' : 'right',
          })
        }
      }
    },
    [isEditing, cellValue, meta],
  )

  const onInputKeyDown = React.useCallback(
    (event: React.KeyboardEvent<HTMLInputElement>) => {
      // Handle backspace when input is empty - remove last selected item
      if (event.key === 'Backspace' && searchValue === '' && selectedValues.length > 0) {
        event.preventDefault()
        const lastValue = selectedValues.at(-1)
        if (lastValue) {
          removeValue(lastValue)
        }
      }
      // Prevent escape from propagating to close the popover immediately
      // Let the command handle it first
      if (event.key === 'Escape') {
        event.stopPropagation()
      }
    },
    [searchValue, selectedValues, removeValue],
  )

  React.useEffect(() => {
    if (isEditing && !open) {
      setOpen(true)
    }
    if (isFocused && !isEditing && !meta?.searchOpen && !meta?.isScrolling && containerRef.current) {
      containerRef.current.focus()
    }
  }, [isFocused, isEditing, open, meta?.searchOpen, meta?.isScrolling])

  // Focus input when popover opens
  React.useEffect(() => {
    if (open && inputRef.current) {
      setTimeout(() => inputRef.current?.focus(), 0)
    }
  }, [open])

  const displayLabels = selectedValues
    .map((val) => options.find((opt) => opt.value === val)?.label ?? val)
    .filter(Boolean)

  const rowHeight = table.options.meta?.rowHeight ?? 'short'

  const lineCount = getLineCount(rowHeight)
  const maxVisibleBadgeCount = lineCount * 3

  const visibleLabels = displayLabels.slice(0, maxVisibleBadgeCount)
  const hiddenBadgeCount = Math.max(0, displayLabels.length - maxVisibleBadgeCount)

  return (
    <DataGridCellWrapper
      ref={containerRef}
      cell={cell}
      table={table}
      rowIndex={rowIndex}
      columnId={columnId}
      isEditing={isEditing}
      isFocused={isFocused}
      isSelected={isSelected}
      onKeyDown={onWrapperKeyDown}
    >
      {isEditing ? (
        <Popover open={open} onOpenChange={onOpenChange}>
          <PopoverAnchor asChild>
            <div className="absolute inset-0" />
          </PopoverAnchor>
          <PopoverContent
            data-grid-cell-editor=""
            align="start"
            sideOffset={sideOffset}
            className="w-[300px] rounded-none p-0"
            onOpenAutoFocus={onOpenAutoFocus}
          >
            <Command className="[&_[data-slot=command-input-wrapper]]:h-auto [&_[data-slot=command-input-wrapper]]:border-none [&_[data-slot=command-input-wrapper]]:p-0 [&_[data-slot=command-input-wrapper]_svg]:hidden">
              <div className="flex min-h-9 flex-wrap items-center gap-1 border-b px-3 py-1.5">
                {selectedValues.map((value) => {
                  const option = options.find((opt) => opt.value === value)
                  const label = option?.label ?? value

                  return (
                    <Badge key={value} variant="secondary" className="h-5 gap-1 px-1.5 text-xs">
                      {label}
                      <button
                        type="button"
                        onClick={(event) => removeValue(value, event)}
                        onPointerDown={(event) => {
                          event.preventDefault()
                          event.stopPropagation()
                        }}
                      >
                        <Cross2Icon className="size-3" />
                      </button>
                    </Badge>
                  )
                })}
                <CommandInput
                  ref={inputRef}
                  value={searchValue}
                  onValueChange={setSearchValue}
                  onKeyDown={onInputKeyDown}
                  placeholder="Search..."
                  className="h-auto flex-1 p-0"
                />
              </div>
              <CommandList className="max-h-full">
                <CommandEmpty>No options found.</CommandEmpty>
                <CommandGroup className="max-h-[300px] scroll-py-1 overflow-y-auto overflow-x-hidden">
                  {options.map((option) => {
                    const isSelected = selectedValues.includes(option.value)

                    return (
                      <CommandItem key={option.value} value={option.label} onSelect={() => onValueChange(option.value)}>
                        <div
                          className={cn(
                            'flex size-4 items-center justify-center rounded-sm border border-neutral-200 border-neutral-900 dark:border-neutral-800 dark:border-neutral-50',
                            isSelected
                              ? 'bg-neutral-900 text-neutral-50 dark:bg-neutral-50 dark:text-neutral-900'
                              : 'opacity-50 [&_svg]:invisible',
                          )}
                        >
                          <CheckIcon className="size-3" />
                        </div>
                        <span>{option.label}</span>
                      </CommandItem>
                    )
                  })}
                </CommandGroup>
                {selectedValues.length > 0 && (
                  <>
                    <CommandSeparator />
                    <CommandGroup>
                      <CommandItem
                        onSelect={clearAll}
                        className="justify-center text-neutral-500 dark:text-neutral-400"
                      >
                        Clear all
                      </CommandItem>
                    </CommandGroup>
                  </>
                )}
              </CommandList>
            </Command>
          </PopoverContent>
        </Popover>
      ) : null}
      {displayLabels.length > 0 ? (
        <div className="flex flex-wrap items-center gap-1 overflow-hidden">
          {visibleLabels.map((label, index) => (
            <Badge key={selectedValues[index]} variant="secondary" className="h-5 shrink-0 px-1.5 text-xs">
              {label}
            </Badge>
          ))}
          {hiddenBadgeCount > 0 && (
            <Badge variant="outline" className="h-5 shrink-0 px-1.5 text-neutral-500 text-xs dark:text-neutral-400">
              +{hiddenBadgeCount}
            </Badge>
          )}
        </div>
      ) : null}
    </DataGridCellWrapper>
  )
}
