import moment from 'moment';
import React from 'react';
import { Locale } from '../../locale-provider';
import { ApolloColumnType } from '../interfaces';

export const generateLabel = <T extends {}>(
  column: ApolloColumnType<T>,
  value: any,
  locale: Locale['ApolloTable'],
) => {
  if (column.filterType === 'input') {
    return value;
  }

  if (column.filterType === 'checkbox') {
    return String(
      value.map(
        (item: string | number | boolean) => column.valueEnum?.find(i => i.value === item)?.label,
      ),
    );
  }

  if (column.filterType === 'radio') {
    return column.valueEnum?.find(item => item.value === value)?.label;
  }

  if (column.filterType === 'select') {
    return column.valueEnum?.find(item => item.value === value)?.label;
  }

  if (column.filterType === 'dateRange') {
    return value.map((item: moment.Moment) => moment(item).format('YYYY-MM-DD')).join(' ~ ');
  }

  if (column.filterType === 'dateTimeRange') {
    return value
      .map((item: moment.Moment) => moment(item).format('YYYY-MM-DD HH:mm:ss'))
      .join(' ~ ');
  }

  if (column.filterType === 'rangeInput') {
    const firstPrefix = (column.fieldProps as any)?.props?.[0].prefix;
    const lastPrefix = (column.fieldProps as any)?.props?.[1].prefix;
    const firstSuffix = (column.fieldProps as any)?.props?.[0].suffix;
    const lastSuffix = (column.fieldProps as any)?.props?.[1].suffix;

    const newValue = value.map((item: string) => (item ? Number(item) : ''));

    if (!newValue[0] && newValue[0] !== 0 && (newValue[1] || newValue[1] === 0)) {
      return (
        <>
          {locale?.lessThan} {firstPrefix}
          {value[1]}
          {firstSuffix}
        </>
      );
    }
    if ((newValue[0] || newValue[0] === 0) && !newValue[1] && newValue[1] !== 0) {
      return (
        <>
          {locale?.moreThan} {lastPrefix}
          {value[0]}
          {lastSuffix}
        </>
      );
    }
    if (newValue[0] === newValue[1]) {
      return (
        <>
          {firstPrefix}
          {value[0]}
          {firstSuffix}
        </>
      );
    }

    return (
      <>
        {firstPrefix}
        {value[0]}
        {firstSuffix} ~ {lastPrefix}
        {value[1]}
        {lastSuffix}
      </>
    );
  }
};
