import { FiltersMap, KeyedItem, PickerState } from '@wix/bex-core';
import React, { ReactNode } from 'react';

import {
  Avatar,
  TableListItem,
  TableListItemColumn,
  Text,
} from '@wix/design-system';
import { ChevronRightLarge } from '@wix/wix-ui-icons-common';
import { PickerListItemProps } from '../PickerListItemProps';
import { st, classes } from './PickerTableListItem.st.css.js';

export interface PickerTableListItemPropsBase
  extends Partial<PickerListItemProps> {
  primaryAction?: ReactNode;
  primaryActionWidth?: TableListItemColumn['width'];
}

export interface PickerTableListItemProps<T, F extends FiltersMap>
  extends PickerTableListItemPropsBase {
  dataHook?: string;
  showDivider?: boolean;
  keyedItem: KeyedItem<T>;
  state: PickerState<T, F>;
  multiple?: boolean;
}

export function PickerTableListItem<T, F extends FiltersMap>(
  props: PickerTableListItemProps<T, F>,
) {
  const {
    dataHook,
    showDivider,
    keyedItem,
    state,
    primaryAction,
    primaryActionWidth = 'auto',
    title,
    subtitle,
    extraNode,
    disabled,
    checkbox,
    multiple,
    options: optionsProp = [],
    ...tableListItemProps
  } = props;
  const { collection } = state;
  const name = collection.itemName(keyedItem.item);

  const { start, end } = optionsProp.reduce(
    (prev, current) => {
      const column: TableListItemColumn = {
        value: undefined,
        ...current,
      };
      if (current.end) {
        prev.end.push(column);
      } else {
        prev.start.push(column);
      }
      return prev;
    },
    {
      start: [] as TableListItemColumn[],
      end: [] as TableListItemColumn[],
    },
  );

  if (!start.length) {
    start.push(
      {
        align: 'left' as const,
        width: '84px',
        value: <Avatar size="size60" name={name} />,
      },
      {
        align: 'left' as const,
        value: <Text dataHook="selector-title">{name}</Text>,
      },
    );
  }

  const options: TableListItemColumn[] = [
    ...start,
    {
      width: primaryActionWidth,
      value: primaryAction || <ChevronRightLarge />,
      align: 'right',
    },
    ...end,
  ];

  return (
    <TableListItem
      className={st(classes.root)}
      verticalPadding="medium"
      dataHook={dataHook}
      {...tableListItemProps}
      options={options}
    />
  );
}
