import { safeIsoDate } from 'src/pages/dashboard/serviceManagement/agentWorkspace/utils';
import {
  type CoordinatorTaskFilters,
  type DownloadTasksReportFormValues,
  type FilterFormValues,
  type ServiceReportParsedFilters,
} from 'src/pages/dashboard/serviceManagement/types';

import { getRelativeDates } from './filters';

export const parseReportFilters = (
  formValues: DownloadTasksReportFormValues,
  appliedFilters: CoordinatorTaskFilters | FilterFormValues | null,
  helpDeskId?: string | null,
): ServiceReportParsedFilters => {
  const formFilters = {
    destinationEmails: [formValues.email],
    initiator: {
      segmentationGroupIds:
        formValues.segmentations.map(segmentation => segmentation.id) || [],
      profileFields:
        formValues.profileFields.map(profileField => profileField.id) || [],
    },
  };

  // Handle null appliedFilters as empty/no filters
  if (!appliedFilters) {
    return {
      initiatorsIn: [],
      agentGroupsIn: [],
      assigneesIn: [],
      helpDesksIn: helpDeskId ? [helpDeskId] : [],
      catalogItemsIn: [],
      statesIn: [],
      createdAtFrom: null,
      createdAtTo: null,
      ...formFilters,
    };
  }

  const { creationDateFrom, creationDateTo } = appliedFilters;
  const dateOptions =
    'dateOptions' in appliedFilters ? appliedFilters.dateOptions : undefined;

  let start: Date | null = null;
  let end: Date | null = null;

  if (dateOptions?.dateRange || !dateOptions) {
    start = creationDateFrom ? new Date(creationDateFrom) : null;
    end = creationDateTo ? new Date(creationDateTo) : null;
  } else if (dateOptions?.lastSevenDays) {
    ({ start, end } = getRelativeDates(7));
  } else if (dateOptions?.lastFourteenDays) {
    ({ start, end } = getRelativeDates(14));
  } else if (dateOptions?.lastThirtyDays) {
    ({ start, end } = getRelativeDates(30));
  }

  const agentGroupsIn =
    'agentGroupsIn' in appliedFilters
      ? appliedFilters.agentGroupsIn?.map(agentGroup => agentGroup.id) || []
      : [];

  return {
    initiatorsIn:
      appliedFilters.initiatorsIn?.map(initiator => initiator.id) || [],
    agentGroupsIn,
    assigneesIn: appliedFilters.agentsIn?.map(agent => agent.id) || [],
    helpDesksIn: helpDeskId ? [helpDeskId] : [],
    catalogItemsIn:
      appliedFilters.serviceItemsIn?.map(serviceItem => serviceItem.id) || [],
    statesIn: appliedFilters.statesIn?.map(state => state.id) || [],
    createdAtFrom: safeIsoDate(start, true),
    createdAtTo: safeIsoDate(end, false),
    ...formFilters,
  };
};
