import { Box, InfoIcon, TableListItem, Text } from '@wix/design-system';
import React, { CSSProperties, useMemo } from 'react';
import { Column } from '../../model';
import { observer } from 'mobx-react-lite';
import { FiltersMap } from '@wix/bex-core';
import { CustomColumnsState } from '../../state';
import { GridCardItemProps } from '../DragAndDrop';
import { useToolbarCollectionContext } from '../ToolbarCollectionContext';
import { useWixPatternsContainer } from '@wix/bex-core/react';

export interface ColumnListTableListItemProps<T, F extends FiltersMap>
  extends GridCardItemProps {
  column: Column;
  state: CustomColumnsState<T, F>;
  showDivider?: boolean;
}

function _ColumnListTableListItem<T, F extends FiltersMap>(
  props: ColumnListTableListItemProps<T, F>,
) {
  const {
    column,
    state,
    showDivider,
    domRef,
    dragging,
    dragHandleProps,
    index,
    rowIndex,
    columnIndex,
    droppable,
    ...rest
  } = props;
  const { select } = state;

  const { collectionDataExtension } = useToolbarCollectionContext();
  const { translate: t } = useWixPatternsContainer();

  const { infoTooltipProps } = column;

  const checkboxDisabled = !column.hideable;
  const hasSearchValue = state.searchValue.trim().length > 0;
  const dragDisabled = column.reorderDisabled || hasSearchValue;
  const checked = select.isChecked(column.id);
  const infoContent =
    infoTooltipProps?.panelContent || infoTooltipProps?.content;

  const style = useMemo<CSSProperties>(
    () => ({
      display: 'flex',
      flexDirection: 'column',
      position: 'relative',
    }),
    [],
  );

  const dataExtensionsCTA = collectionDataExtension?.DataExtension
    ?.CustomColumnsEditCustomFieldCTAButton &&
    column.dataExtension &&
    column.dataExtension.editable && (
      <collectionDataExtension.DataExtension.CustomColumnsEditCustomFieldCTAButton
        field={column.dataExtension}
      />
    );

  return (
    <div
      {...rest}
      ref={domRef}
      style={style}
      data-hook={`column-item-${column.id}`}
    >
      <TableListItem
        showDivider={showDivider}
        checkbox
        checked={checked}
        verticalPadding="tiny"
        checkboxDisabled={checkboxDisabled}
        checkboxTooltipContent={
          checkboxDisabled
            ? dragDisabled
              ? t('cairo.table.custom-columns.disabled.tooltip')
              : t('cairo.table.custom-columns.hidden.disabled.tooltip')
            : undefined
        }
        checkboxTooltipProps={{
          maxWidth: '400px',
          appendTo: 'window',
          disabled: !checkboxDisabled,
        }}
        onCheckboxChange={() => {
          if (checkboxDisabled) {
            return;
          }
          state.onColumnCheckboxToggle(column);
          state.customizeColumnsInSidePanelBi({ actionName: 'visibility' });
        }}
        {...(hasSearchValue
          ? {}
          : {
              draggable: true,
              dragging,
              dragDisabled,
              dragHandleProps: {
                ...dragHandleProps,
                tooltipContent: dragDisabled
                  ? checkboxDisabled
                    ? t('cairo.table.custom-columns.disabled.tooltip')
                    : t('cairo.table.custom-columns.move.disabled.tooltip')
                  : undefined,
                tooltipProps: {
                  maxWidth: '400px',
                  appendTo: 'window',
                },
              },
            })}
        options={[
          {
            value: (
              <Box>
                <div
                  style={{
                    padding: '0 6px',
                    cursor: checkboxDisabled ? undefined : 'pointer',
                    wordBreak: 'break-word',
                  }}
                  onClick={() => {
                    if (checkboxDisabled) {
                      return;
                    }
                    state.onColumnCheckboxToggle(column);
                  }}
                >
                  <Text size="small" dataHook="tableListItem-label">
                    {column.name || column.title || column.id}
                  </Text>
                </div>

                <div
                  style={{ cursor: 'default' }}
                  onPointerDown={(e) => e.stopPropagation()}
                >
                  {infoContent && (
                    <InfoIcon
                      size="small"
                      {...infoTooltipProps}
                      dataHook="info-icon"
                      content={infoContent}
                    />
                  )}
                </div>
              </Box>
            ),
          },

          ...(dataExtensionsCTA
            ? [
                {
                  value: dataExtensionsCTA,
                  align: 'right' as const,
                },
              ]
            : []),
        ]}
      />
    </div>
  );
}

export const ColumnListTableListItem = observer(_ColumnListTableListItem);
