import * as React from 'react'

import { Checkbox } from '@components/ui/checkbox/checkbox'
import { DataGridCellWrapper } from '@components/ui/data-grid/data-grid-cell-wrapper'

import { CellVariantProps } from './cell-variant-types'

export function CheckboxCell<TData>({
  cell,
  table,
  rowIndex,
  columnId,
  isFocused,
  isSelected,
}: Readonly<CellVariantProps<TData, boolean>>) {
  const initialValue = cell.getValue()
  const [value, setValue] = React.useState(Boolean(initialValue))
  const containerRef = React.useRef<HTMLDivElement>(null)
  const meta = table.options.meta
  const colMeta = cell.column.columnDef.meta
  // Normalize editable to a resolver function and memoize to avoid typeof checks per cell
  const editableResolver = React.useMemo(() => {
    const v = colMeta?.editable
    if (v === undefined) {
      return () => true
    }
    return typeof v === 'function' ? (v as (row: TData) => boolean) : () => Boolean(v)
  }, [colMeta?.editable])
  const isEditable = editableResolver(cell.row.original)

  const onCheckedChange = React.useCallback(
    (checked: boolean) => {
      setValue(checked)
      meta?.onDataUpdate?.({ rowIndex, columnId, value: checked })
    },
    [meta, rowIndex, columnId],
  )

  const onWrapperKeyDown = React.useCallback(
    (event: React.KeyboardEvent<HTMLDivElement>) => {
      if (!isEditable) {
        return
      }
      if (isFocused && (event.key === '' || event.key === 'Enter')) {
        event.preventDefault()
        event.stopPropagation()
        onCheckedChange(!value)
      }
    },
    [isFocused, value, onCheckedChange, isEditable],
  )

  React.useEffect(() => {
    setValue(Boolean(initialValue))
  }, [initialValue])

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

  const onWrapperClick = React.useCallback(
    (event: React.MouseEvent) => {
      if (!isEditable) {
        return
      }
      if (isFocused) {
        event.preventDefault()
        event.stopPropagation()
        onCheckedChange(!value)
      }
    },
    [isFocused, value, onCheckedChange, isEditable],
  )

  const onCheckboxClick = React.useCallback((event: React.MouseEvent) => {
    event.stopPropagation()
  }, [])

  const onCheckboxMouseDown = React.useCallback((event: React.MouseEvent<HTMLInputElement>) => {
    event.stopPropagation()
  }, [])

  const onCheckboxDoubleClick = React.useCallback((event: React.MouseEvent<HTMLInputElement>) => {
    event.stopPropagation()
  }, [])

  return (
    <DataGridCellWrapper
      ref={containerRef}
      cell={cell}
      table={table}
      rowIndex={rowIndex}
      columnId={columnId}
      isEditing={false}
      isFocused={isFocused}
      isSelected={isSelected}
      onClick={onWrapperClick}
      onKeyDown={onWrapperKeyDown}
      className="flex size-full justify-center"
    >
      <Checkbox
        variant="simple"
        iconStyle="simple"
        checkIcon="check"
        checked={value}
        onChange={(e) => onCheckedChange(e.target.checked)}
        onClick={onCheckboxClick}
        onMouseDown={onCheckboxMouseDown}
        onDoubleClick={onCheckboxDoubleClick}
        className="border-neutral-900 dark:border-neutral-50"
      />
    </DataGridCellWrapper>
  )
}
