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

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

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

  useEffect(() => {
    if (cellRef.current) {
      const link = cellRef.current.getElementsByTagName('a')[0];
      if (link) {
        link.onclick = focusCurrentCell;
      }
    }
  }, []);

  useEffect(() => {
    if (tableRef.current?.contains(document.activeElement)) {
      const link = cellRef.current?.getElementsByTagName('a')[0];

      if (link) {
        if (isCurrentCellFocused) {
          link.focus();
          link.tabIndex = 0;
        } else {
          link.tabIndex = -1;
        }
      }
    }
  }, [isCurrentCellFocused]);

  return (
    <div
      ref={cellRef}
      id={
        (props.cell.column.columnDef as EditableTableColumnDef<TData>)?.columnType === 'th'
          ? `${props.cell.row.id}-id`
          : ''
      }
      className="td-content px-2 py-0.5 outline-purple-600"
    >
      {flexRender(props.cell.column.columnDef.cell, {
        ...props.cell.getContext(),
      })}
    </div>
  );
}
