import {
  parseSegmentations,
  safeIsoDate,
} from 'src/pages/dashboard/serviceManagement/agentWorkspace/utils';
import { OXXO_SEGMENTATION_OPTIONS } from 'src/pages/dashboard/serviceManagement/constants';
import {
  type FilterFormValues,
  type OxxoCollaboratorType,
  type TaskFiltersHydrated,
  type ViewForm,
} from 'src/pages/dashboard/serviceManagement/types';
import { emptyArrayToNull } from 'src/utils/arrays';
import { type LokaliseTFunction } from 'src/utils/i18n';

import { normalizeDateHours } from './date';
import { getStateName } from './state';

export const parseCreateViewFormValues = (formValues: ViewForm) => {
  const statesIn = emptyArrayToNull(formValues.statesIn.map(state => state.id));
  const catalogItemsIn = formValues.serviceItemsIn
    ? emptyArrayToNull(
        formValues.serviceItemsIn.map(serviceItem => serviceItem.id),
      )
    : null;
  const initiatorsIn = emptyArrayToNull(
    formValues.initiatorsIn.map(initiator => initiator.id),
  );
  const agentsIn = emptyArrayToNull(formValues.agentsIn.map(agent => agent.id));

  return {
    name: formValues.name || null,
    filters: {
      statesIn,
      catalogItemsIn,
      createdAtFrom: safeIsoDate(formValues.creationDateFrom, true),
      createdAtTo: safeIsoDate(formValues.creationDateTo, false),
      initiatorsIn,
      agentsIn,
      initiatorSegmentations: parseSegmentations(
        formValues.initiatorCollaboratorTypesIn,
        false,
      ),
    },
  };
};

export const decodeViewInitiatorSegmentations = (
  initiatorSegmentations: Record<string, number[]> | null,
) => {
  if (!initiatorSegmentations || !Object.keys(initiatorSegmentations).length) {
    return [];
  }
  const items: OxxoCollaboratorType[] = [];
  Object.entries(initiatorSegmentations).forEach(([, value]) => {
    value.filter(Boolean).forEach(itemId => {
      items.push({
        id: itemId,
        title:
          OXXO_SEGMENTATION_OPTIONS.items.find(item => item.id === itemId)
            ?.title ?? '',
      });
    });
  });
  return items;
};

export const normalizeViewFilters = (
  viewFilters: TaskFiltersHydrated,
  t: LokaliseTFunction,
): FilterFormValues => {
  return {
    statesIn:
      viewFilters.statesIn?.map(state => ({
        id: state.id,
        name: state.name,
        terminal: state.terminal,
        title: t(getStateName(state.name)),
      })) || [],
    serviceItemsIn:
      viewFilters.catalogItemsIn?.map(item => ({
        id: item.id,
        title: item.name,
        name: item.name,
      })) || [],
    creationDateFrom: viewFilters.createdAtFrom
      ? normalizeDateHours(new Date(viewFilters.createdAtFrom))
      : null,
    creationDateTo: viewFilters.createdAtTo
      ? normalizeDateHours(new Date(viewFilters.createdAtTo))
      : null,
    initiatorsIn:
      viewFilters.initiatorsIn?.map(initiator => ({
        id: initiator.id,
        firstName: initiator.firstName,
        lastName: initiator.lastName,
        profilePicture: initiator.profilePicture,
        employeeInternalId: initiator.employeeInternalId,
      })) || [],
    agentsIn:
      viewFilters.assigneesIn?.map(assignee => ({
        id: assignee.id,
        firstName: assignee.firstName,
        lastName: assignee.lastName,
        profilePicture: assignee.profilePicture,
        employeeInternalId: assignee.employeeInternalId,
      })) || [],
    initiatorCollaboratorTypesIn: decodeViewInitiatorSegmentations(
      viewFilters.initiatorSegmentations,
    ),
  };
};
