import React, { useMemo, useRef } from 'react';
import { observer } from 'mobx-react-lite';
import { GlobalAudioPlayer } from '@wix/patterns-fields';
import { PatternsFieldsProvider } from '../../providers/PatternsFieldsProvider';
import type { FiltersMap, OptionalFiltersMap } from '@wix/bex-core';
import { TableVirtual, type TableVirtualProps } from '../Table/TableVirtual';
import {
  type EditableColumn,
  EditableTableState,
} from '../../state/EditableTable';
import { EditableCell } from './EditableCell';
import { EditableTableContextMenu } from './EditableTableContextMenu';
import { useEditableTableContextMenu } from './useEditableTableContextMenu';
import { MessageActionModal } from '../ActionModal';
import { useEditableTableCollectionSyncProps } from './useEditableTableCollectionSyncProps';
import { useKeyboardNavigation } from './useKeyboardNavigation';
import { useClipboardHandler } from './useClipboardHandler';
import { useClearFocusOnBlur } from './useClearFocusOnBlur';
import { useMouseSweepSelection } from './useMouseSweepSelection';
import { AddItemRow } from './AddItemRow';
import { useAddRow } from './useAddRow';
import type { TableColumn } from '../../model';
import { useHeaderActions } from './useHeaderActions';

export interface EditableTableProps<
  T,
  F extends FiltersMap = OptionalFiltersMap,
> extends Omit<
    TableVirtualProps<T, F>,
    | 'columns'
    | 'state'
    | 'onRowClick'
    | 'forceResize'
    | 'horizontalScroll'
    | 'showSelection'
    | 'showRowNumbers'
  > {
  /** EditableTableState instance, created via useEditableTableCollection */
  state: EditableTableState<T, F>;

  /** Column definitions with cell types */
  columns: EditableColumn<T>[];

  /** When true, hides the built-in header actions popover for all columns. */
  hideHeaderActions?: boolean;

  /** data-hook for testkit selectors */
  dataHook?: string;
}

function _EditableTable<T, F extends FiltersMap = OptionalFiltersMap>(
  props: EditableTableProps<T, F>,
) {
  const {
    state,
    columns: editableColumns,
    hideHeaderActions,
    dataHook,
    children,
    ...tableBaseProps
  } = props;

  useEditableTableCollectionSyncProps(props);

  const containerRef = useRef<HTMLDivElement>(null);

  const keyboard = useKeyboardNavigation(state);
  useClipboardHandler(state, containerRef);
  const { onFocus, onBlur } = useClearFocusOnBlur(state.cellInteraction);
  useMouseSweepSelection(state, containerRef);

  const builtInActions = useHeaderActions(
    state,
    editableColumns,
    hideHeaderActions,
  );

  const { showAddItemRow, handleAddItem } = useAddRow(state);

  const tableColumns = useMemo(
    () =>
      editableColumns.map((col) => ({
        ...col,
        name: col.name ?? (typeof col.title === 'string' ? col.title : col.id),
        titleSuffix: builtInActions[col.id],
        render: (_item: T, rowNum: number) => {
          const rowKey = state.keyedItems[rowNum]?.key;
          return rowKey ? (
            <EditableCell state={state} rowKey={rowKey} columnId={col.id} />
          ) : null;
        },
      })) as TableColumn<T>[],
    [editableColumns, state, builtInActions],
  );

  const contextMenu = useEditableTableContextMenu(state.cellInteraction);

  return (
    <PatternsFieldsProvider>
      <div
        ref={containerRef}
        data-hook={dataHook}
        tabIndex={0}
        onKeyDown={keyboard.onKeyDown}
        onFocus={onFocus}
        onBlur={onBlur}
        onContextMenu={contextMenu.handleContextMenu}
      >
        <TableVirtual
          {...tableBaseProps}
          state={state.tableState}
          columns={tableColumns}
          forceResize
          horizontalScroll
          showSelection
          showRowNumbers
        >
          {showAddItemRow && <AddItemRow onAdd={handleAddItem} />}
        </TableVirtual>
      </div>
      <EditableTableContextMenu
        state={state}
        position={contextMenu.position}
        cell={contextMenu.cell}
        menuRef={contextMenu.menuRef}
        onClose={contextMenu.handleClose}
      />
      {state.deleteConfirmModal.value && (
        <MessageActionModal
          state={state.deleteConfirmModal}
          {...state.deleteConfirmModal.value}
        />
      )}
      {state.fieldActions.confirmModal.value && (
        <MessageActionModal
          state={state.fieldActions.confirmModal}
          {...state.fieldActions.confirmModal.value}
          primaryButtonProps={{
            ...state.fieldActions.confirmModal.value.primaryButtonProps,
            disabled: state.fieldActions.deleteTask.status.isLoading,
          }}
        />
      )}
      {children}
      <GlobalAudioPlayer />
    </PatternsFieldsProvider>
  );
}

export const EditableTable = observer(_EditableTable);
