import { FC } from 'react';
import { useI18n } from 'mystique/hooks/useI18n';
import { recursiveValueDecorator } from 'mystique/utils';
import { ListColumn, ListProps } from 'mystique/components/List';
import { TranslatableString } from 'mystique/types/common';
import {
  ComponentRegistry,
  StdProps,
} from 'mystique/registry/ComponentRegistry';
import { QuantitySelectorComponentProps } from 'mystique/components/QuantitySelectorComponent';
import { BarcodeFilterProps } from 'mystique/components/QuantityList';

interface ScannerContract extends BarcodeFilterProps {
  highlightRow?: number;
}

export interface QuantityListProps extends ListProps {
  /**
   * The properties of the quantity selector component. Since data is not needed, this is marked as an partial interface of Quantity Selector Component
   */
  quantitySelectorProps?: Partial<QuantitySelectorComponentProps>;
  /**
   * Optional configuration for the quantity selector attribute
   */
  quantitySelectorAttribute?: Partial<TranslatableAttribute>;
  /**
   * The attributes to show on each column of the list.
   */
  attributes: TranslatableAttribute[];
  /**
   * The props sent to the barcode filter component
   */
  scannerProps?: ScannerContract;
}

// Don't publish this in docs.
export type TranslatableAttribute = ListColumn & {
  label: TranslatableString;
  labelFallback?: string;
};

export const QuantityList: FC<QuantityListProps> = ({
  scannerProps,
  quantitySelectorAttribute,
  ...props
}) => {
  const { quantitySelectorProps, attributes } = props;
  const { prefixedTranslate } = useI18n();

  const quantitySelectorAttr: TranslatableAttribute = {
    label:
      'i18n:fc.sf.ui.returns.orders.createReturnOrder.list.column.returnQty.label',
    labelFallback: 'Return Qty',
    align: 'center',
    ...quantitySelectorAttribute,
    type: 'component',
    options: {
      component: 'fc.se.quantity.selector',
      props: quantitySelectorProps,
    },
  };

  let modifiedAttributes = [...attributes, quantitySelectorAttr];
  for (const attr of modifiedAttributes) {
    attr.label = prefixedTranslate([
      attr.label,
      attr.labelFallback || attr.label,
    ]);
  }
  modifiedAttributes = recursiveValueDecorator(
    modifiedAttributes,
    'string',
    prefixedTranslate,
  );

  const Scanner = ComponentRegistry.get<ScannerContract & StdProps>(
    'fc.scanner.barcodeFilter',
  );

  const List = ComponentRegistry.get<ListProps & StdProps>(
    'fc.list',
  ) as FC<ListProps>;

  return (
    <>
      {Scanner && <Scanner {...scannerProps} />}
      <List
        {...props}
        attributes={modifiedAttributes}
        // @ts-ignore
        noRecordKey={Scanner ? 'fc.barcodeFilter.list.noRecords' : undefined}
      />
    </>
  );
};
