import { IsEmpty, NumberFormat } from '@devesharp/react-utils';
import { format } from 'date-fns';
import * as _ from 'lodash';
import { ETagFilterType, ITagFilter } from './TagsFilters.interface';

export function generateTagsFilters(filters: any, filtersSchema: any): ITagFilter[] {
   const tags = Object.entries(filters || {})
      // Key precisa ter schema definido, se não é ignorado
      .filter(([key]) => filtersSchema[key])
      // Se filter estiver vazio ou for o valor default do schema é removido
      .filter(
         ([key, value]) =>
            (!IsEmpty(value) && !_.isEqual(value, filtersSchema[key].default)) || value === 0 || value === '0',
      )
      // Se filter for um dos ignore deve ser removido
      .filter(([key, value]) =>
         filtersSchema[key].ignore
            ? filtersSchema[key].ignore.map((e) => e.toString()).indexOf(filters[key].toString())
            : true,
      )
      // Faz o tratamento
      .map(([key, value]) => {
         const filtersSchemaKey: any = filtersSchema[key] ?? {};

         let modifierValue = value;
         let calendarDate: any;

         switch (filtersSchemaKey.type) {
            case ETagFilterType.Select:
               return {
                  key,
                  type: filtersSchemaKey.type,
                  default: filtersSchemaKey.default || '',
                  value: filtersSchemaKey.values[filters[key]],
               };
            case ETagFilterType.Location:
               return (value as string).split('_').map((i) => {
                  const location = i.split(',');
                  let locationString: string;

                  if (location.length === 3) {
                     const [estate, city, neighborhood] = location;
                     locationString = `${neighborhood} - ${city}, ${estate}`;
                  } else if (location.length === 2) {
                     const [estate, city] = location;
                     locationString = `${city}, ${estate}`;
                  } else {
                     return null;
                  }

                  return {
                     key,
                     type: 'location',
                     parentValue: filters[key],
                     value: locationString,
                     locationValue: i,
                     values: value,
                  };
               });
            case ETagFilterType.CheckBox:
               return (value as any[])
                  .map((i) => {
                     return filtersSchemaKey.values[i]
                        ? {
                             key,
                             type: 'checkbox',
                             default: false,
                             checkboxValue: i,
                             parentValue: filters[key],
                             value: filtersSchemaKey.values[i],
                             values: value,
                          }
                        : null;
                  })
                  .filter((i) => !IsEmpty(i));
            case ETagFilterType.Date:
               return {
                  key,
                  type: 'input',
                  prefix: filtersSchemaKey.prefix ?? '',
                  suffix: filtersSchemaKey.suffix ?? '',
                  value: format(value as Date, filtersSchemaKey.format || 'dd/MM/yyyy'),
                  default: filtersSchemaKey.default ?? '',
               };
            case ETagFilterType.Input:
            case ETagFilterType.InputNumber:
            case ETagFilterType.InputPrice:
            default:
               if (filtersSchemaKey.type === 'price') {
                  const decimals = filtersSchemaKey.decimals || 2;
                  modifierValue = NumberFormat(Number(modifierValue), decimals).toString();
               }
               if (filtersSchemaKey.type === 'number') {
                  const decimals = filtersSchemaKey.decimals || 0;
                  modifierValue = NumberFormat(Number(modifierValue), decimals).toString();
               }

               return {
                  key,
                  type: 'input',
                  prefix: filtersSchemaKey.prefix ?? '',
                  suffix: filtersSchemaKey.suffix ?? '',
                  value: modifierValue,
                  default: filtersSchemaKey.default ?? '',
               };
         }
      })
      .filter((i) => !IsEmpty(i))
      .map((tag) => tag as ITagFilter);

   return _.flattenDeep(tags);
}
