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 { CustomColumnsPanelStateBase } from '../../state/CustomColumnsPanelStateBase';
import { FiltersMap } from '@wix/bex-core';
import { GridCardItemProps } from '../DragAndDrop';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import { getFieldTypeIcon } from '../../utils/fieldTypePrefixIcons';
import { FieldIndications } from './FieldIndications';
import { FieldActionsPopover } from '../FieldActions';

export interface ColumnListTableListItemProps<T, F extends FiltersMap>
  extends GridCardItemProps {
  column: Column;
  state: CustomColumnsPanelStateBase<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 { collectionFieldsSource } = state;
  const { translate: t } = useWixPatternsContainer();
  const showFieldTypeIcons = state.showFieldTypeIcons;

  const { infoTooltipProps } = column;
  const prefixIcon = showFieldTypeIcons
    ? getFieldTypeIcon({ fieldType: column.fieldType })
    : null;

  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 isRequired =
    column.validation?.some((r) => r.type === 'required') ?? false;
  const style = useMemo<CSSProperties>(
    () => ({
      display: 'flex',
      flexDirection: 'column',
      position: 'relative',
    }),
    [],
  );

  // The source field is stamped on the column at projection time. The source
  // builds the per-field manage menu (edit / delete / archive …) as data; we
  // render it with the shared popover. Null when the field has no menu.
  const menuConfig = column.field
    ? collectionFieldsSource?.fieldActionsMenu?.({
        fieldId: column.field.id,
        origin: 'Custom columns panel',
        location: 'Customize columns action cell',
      })
    : undefined;
  const manageFieldMenu = menuConfig ? (
    <FieldActionsPopover {...menuConfig} />
  ) : null;

  const hasIndications =
    column.isPii ||
    column.isPrimary ||
    column.isSystem ||
    !!column.dataExtension;
  const hasRightContent = hasIndications || !!manageFieldMenu;

  return (
    <div
      {...rest}
      ref={domRef}
      style={style}
      data-hook={`column-item-${column.id}`}
    >
      <TableListItem
        showDivider={showDivider}
        checkbox
        checked={checked}
        verticalPadding="tiny"
        horizontalPadding="small"
        dragHandleSize="small"
        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
                {...(prefixIcon ? { verticalAlign: 'middle' } : {})}
                minWidth={0}
                flexGrow={1}
              >
                <div
                  style={{
                    ...(prefixIcon
                      ? { display: 'flex', alignItems: 'center' }
                      : {}),
                    padding: '0',
                    cursor: checkboxDisabled ? undefined : 'pointer',
                    overflow: 'hidden',
                    minWidth: 0,
                  }}
                  onClick={() => {
                    if (checkboxDisabled) {
                      return;
                    }
                    state.onColumnCheckboxToggle(column);
                  }}
                >
                  {prefixIcon && (
                    <Box
                      align="center"
                      verticalAlign="middle"
                      marginRight="SP1"
                      flexShrink={0}
                    >
                      {prefixIcon}
                    </Box>
                  )}
                  <Text
                    size="small"
                    weight="normal"
                    dataHook="tableListItem-label"
                    ellipsis
                    appendTo="window"
                  >
                    {column.name || column.title || column.id}
                  </Text>
                  {isRequired && (
                    <Text size="tiny" skin="error" weight="bold">
                      &nbsp;*
                    </Text>
                  )}
                </div>

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

          ...(hasRightContent
            ? [
                {
                  value: (
                    <Box gap="SP1" verticalAlign="middle">
                      <FieldIndications column={column} />
                      {manageFieldMenu}
                    </Box>
                  ),
                  align: 'right' as const,
                  width: 'auto',
                },
              ]
            : []),
        ]}
      />
    </div>
  );
}

export const ColumnListTableListItem = observer(_ColumnListTableListItem);
