import { type Cell, flexRender } from '@tanstack/react-table';
import { useEffect, useRef } from 'react';
import type { CheckBoxMetaData, EditableTableColumnDef } from '../types';
import { useFocusHandler } from '../focus-handler/focus-handler-provider';
import { CellTypes } from '../constants';
import { useTableContext } from '../table-context/table-context-provider';

interface EditableCheckBoxProps<TData> {
  cell: Cell<TData, unknown>;
}
export default function EditableCheckBox<TData>(props: EditableCheckBoxProps<TData>) {
  const cellRef = useRef<HTMLDivElement>(null);

  const { isCurrentCellFocused, focusCurrentCell } = useFocusHandler({
    cellType: CellTypes.dataCell,
    columnIndex: props.cell.column.getIndex(),
    groupId: null,
    rowId: props.cell.row.id,
    rowIndex: props.cell.row.index,
  });

  const { tableRef } = useTableContext();

  const metaData = (props.cell.column.columnDef as EditableTableColumnDef<TData>)
    .meta as CheckBoxMetaData<TData>;

  const onKeyDown = (e: React.KeyboardEvent) => {
    const tableWrapper = tableRef.current;
    const activeElement = document.activeElement;

    // If we're in an input that's not part of our table, ignore all keydowns
    if (
      (activeElement &&
        activeElement.tagName === 'INPUT' &&
        !tableWrapper?.contains(activeElement)) ||
      e.key === 'Tab'
    ) {
      return;
    }
  };

  useEffect(() => {
    if (isCurrentCellFocused && tableRef.current?.contains(document.activeElement)) {
      cellRef.current?.focus();
    }
  }, [isCurrentCellFocused]);

  return (
    <div
      {...(metaData.label
        ? { 'aria-label': metaData.label(props.cell.row.original) }
        : { 'aria-labelledby': props.cell.row.id })}
      // biome-ignore lint/a11y/useSemanticElements: <explanation>
      role="checkbox"
      aria-checked={props.cell.row.getIsSelected()}
      ref={cellRef}
      className="td-content flex h-6 w-6 items-center justify-center outline-purple-600"
      onClick={(e) => {
        // If user clicked directly on <input>, don't trigger another click
        if ((e.target as HTMLElement).tagName.toLowerCase() === 'input') {
          focusCurrentCell();
          return;
        }

        const checkbox = cellRef.current?.querySelector('input[type="checkbox"]');
        (checkbox as HTMLInputElement)?.click();
        focusCurrentCell();
      }}
      onKeyDown={(e) => {
        if (e.key === 'Enter' || e.key === ' ') {
          e.preventDefault();
          const checkbox = cellRef.current?.querySelector('input[type="checkbox"]');
          if (checkbox) {
            (checkbox as HTMLInputElement).click();
          }
        }
        onKeyDown(e);
      }}
      tabIndex={isCurrentCellFocused ? 0 : -1}
    >
      {flexRender(props.cell.column.columnDef.cell, {
        ...props.cell.getContext(),
        tabIndex: -1,
      })}
    </div>
  );
}
