import moment from "moment";
import CenterPhoneList from "../components/center-phone/CenterPhoneList";
import http from "../http-common";

const getAllEvents = (params) => {
  return http.get('/events', { params});
};

const getByCustomer = (params) => {
  return http.get('/events/getByCustomer', {params})
};

const createNewEvent = (data) => {
  data.status = 'active';
	return http.post('/events', data);
};


const updateEvent = (id, data) => {
  return http.put(`/events/${id}`, data);
}

const disableEvent = (id, data) => {
  return http.put(`/events/${id}/disable`, data);
}

const getEvent = (id) => {
  return http.get(`/events/${id}`);
}

const deleteEvent = (id) => {
  return http.delete(`/events/${id}`)
}

const assignTransportationToEvents = (data) => {
  return http.post(`/events/assign`, data);
}

// Event Recurrence API
const getAllEventRecurrences = () => {
  return http.get('/event-recurrences');
};

const createEventRecurrence = (data) => {
  return http.post('/event-recurrences', data);
};

const updateEventRecurrence = (id, data) => {
  return http.put(`/event-recurrences/${id}`, data);
};

const disableEventRecurrence = (id, data) => {
  return http.put(`/event-recurrences/${id}/disable`, data);
};

const deleteEventRecurrence = (id) => {
  return http.delete(`/event-recurrences/${id}`);
};

const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const localDate = `${year}-${month}-${day}`;
  return localDate;
};

const getTimeData = () => {
  return http.get(`/timedata/get-by-condition1`, {
      params: {
        date: moment(new Date()).format('YYYY-MM-DD')
      }
    });
}

const getTransportationInfo = (eventsList, item, timeDocs = []) => {
  const today = new Date();
  // const timeDocs = (await http.get(`/timedata/get-by-condition1`, {
  //   params: {
  //     date: moment(today).format('YYYY-MM-DD')
  //   }
  // }))?.data;
  
  const futureEvents = eventsList.filter((d) => new Date(d.start_time) >= new Date(today.toLocaleDateString()) );
  const isFutureEvent = (event) => futureEvents.find((fe) => fe.id === event.id);
  const futureEventsGroupMap = new Map();
  for (const e of futureEvents) {
    const eDateString = new Date(e.start_time).toLocaleDateString();
    if (futureEventsGroupMap.has(eDateString)) {
      futureEventsGroupMap.set(eDateString, [...futureEventsGroupMap.get(eDateString), e])
    } else {
      futureEventsGroupMap.set(eDateString, [e]);
    }
  }
  return {
    maxTranslate1: timeDocs.find(timeDoc => moment(timeDoc.time).format('YYYY-MM-DD') == moment(item.start_time).format('YYYY-MM-DD'))?.translate1_number || 0,
    maxTranslate2: timeDocs.find(timeDoc => moment(timeDoc.time).format('YYYY-MM-DD') == moment(item.start_time).format('YYYY-MM-DD'))?.translate2_number || 0,
    maxResource: timeDocs.find(timeDoc => moment(timeDoc.time).format('YYYY-MM-DD') == moment(item.start_time).format('YYYY-MM-DD'))?.max_resource_number || 0,
    totalTranslate1: futureEventsGroupMap.get(new Date(item?.start_time).toLocaleDateString())?.filter(e => e.interpreter === '1(译)')?.length,
    totalTranslate2: futureEventsGroupMap.get(new Date(item?.start_time).toLocaleDateString())?.filter(e => e.interpreter === '2(译)')?.length,
    totalResource: [... new Set(futureEventsGroupMap.get(new Date(item?.start_time).toLocaleDateString())?.map(e => e.source_uuid))]?.length,
    isFutureEvent: isFutureEvent(item)
  }
}

// Language Support options
const languageSupportOptions = [
  {
    value: 'Checkin',
    label: 'Checkin'
  },
  {
    value: 'Center',
    label: 'Center',
  },
  {
    value: 'Family',
    label: 'Family'
  },
  {
    value: 'Office',
    label: 'Office in person'
  },
  {
    value: 'Office(Phone)',
    label: 'Office by phone'
  },
  {
    value: 'Nurse',
    label: 'Nurse'
  }
];

// Legacy alias for backward compatibility
const interpreterLevelOptions = languageSupportOptions;

// Label options for Medical Events
const labelOptions = [
  {
    value: 'red',
    label: 'Eyes-On'
  },
  {
    value: 'pink',
    label: 'Self-Transport',
  },
  {
    value: 'green',
    label: 'Televisit'
  },
  {
    value: 'blue',
    label: 'Default for By Center'
  },
  {
    value: 'black',
    label: 'Medication Pickup Only'
  },
  {
    value: 'purple',
    label: 'Drop-Off Only',
  },
  {
    value: 'gray',
    label: 'Deleted Appt'
  },
  {
    value: 'orange',
    label: 'Pick-Up Only'
  },
  {
    value: 'brown',
    label: 'Translation By Center'
  }
];

// Activity color options
const activityColorOptions = [
  {
    value: 'red',
    label: 'Classes'
  },
  {
    value: 'pink',
    label: 'Games'
  },
  {
    value: 'green',
    label: 'Events'
  },
  {
    value: 'blue',
    label: 'Outings'
  },
  {
    value: 'purple',
    label: 'Personal Care'
  },
  {
    value: 'brown',
    label: 'Care Activities'
  }
];

// Incident/Attendance Notes color options (always blue)
const incidentColorOptions = [
  {
    value: 'blue',
    label: 'Attendance Note'
  }
];

// Meal Plan color options
const mealPlanColorOptions = [
  {
    value: 'brown',
    label: 'Breakfast'
  },
  {
    value: 'green',
    label: 'Lunch'
  },
  {
    value: 'red',
    label: 'Snack'
  }
];

// Legacy alias for backward compatibility
const colorOptions = labelOptions;

// Important Dates legend options (two visual groups)
const importantDatesLegendOptions = [
  {
    value: 'member_related',
    label: 'Member-Related'
  },
  {
    value: 'vehicle_maintenance',
    label: 'Vehicle Maintenance'
  }
];

// Important Dates filter options (matching the title dropdown in the creation popup)
const importantDatesFilterOptions = [
  {
    value: 'birthday',
    label: 'Birthday',
    group: 'member_related'
  },
  {
    value: 'adcaps_completion',
    label: 'ADCAPS Completion',
    group: 'member_related'
  },
  {
    value: 'center_qualification_expiration',
    label: 'Center Qualification Expiration',
    group: 'member_related'
  },
  {
    value: 'oil_change',
    label: 'Oil Change',
    group: 'vehicle_maintenance'
  },
  {
    value: 'monthly_vehicle_inspection',
    label: 'Monthly Vehicle Inspection',
    group: 'vehicle_maintenance'
  },
  {
    value: 'emissions_inspection',
    label: 'Emissions Inspection',
    group: 'vehicle_maintenance'
  },
  {
    value: 'insurance_expiration',
    label: 'Insurance Expiration',
    group: 'vehicle_maintenance'
  },
  {
    value: 'license_plate_expiration',
    label: 'License Plate Expiration',
    group: 'vehicle_maintenance'
  }
];

// Transportation Support options
const transportationTypeOptions = [
  {
    value: 'by own',
    label: 'ByOwn'
  },
  {
    value: 'televisit',
    label: 'Televisit'
  },
  {
    value: 'client does not need to go',
    label: 'Client Does Not need to Go'
  },
  {
    value: 'dropoff only',
    label: 'DropOff Only'
  },
  {
    value: 'pickup only',
    label: 'Pickup Only'
  },
  {
    value: 'Center Transportation',
    label: 'By Center Transportation'
  }
];



const baseUrl = (window.location.hostname.includes('ws1') ||window.location.hostname.includes('localhost') || window.location.hostname.includes('site1')) ? "https://ws1-tspt.mayosolution.com/api" : ((window.location.hostname.includes('ws3') || window.location.hostname.includes('site3')) ? "https://ws3-tspt.mayosolution.com/api" : "https://ws2-tspt.mayosolution.com/api")
// const baseUrl = (window.location.hostname.includes('worldshine.mayo.llc') ||window.location.hostname.includes('worldshine1') || window.location.hostname.includes('site1')) ? "https://worldshine.mayo.llc/api" : ((window.location.hostname.includes('worldshine3') || window.location.hostname.includes('site3')) ? "https://worldshine3.mayo.llc/api" : "https://worldshine2.mayo.llc/api")

const site = (window.location.hostname.includes('ws1') ||window.location.hostname.includes('localhost') || window.location.hostname.includes('site1')) ? 1 : ((window.location.hostname.includes('ws3') || window.location.hostname.includes('site3')) ? 3 : 2)
//const site = (window.location.hostname.includes('worldshine.mayo.llc') ||window.location.hostname.includes('worldshine1') || window.location.hostname.includes('site1')) ? 1 : ((window.location.hostname.includes('worldshine3') || window.location.hostname.includes('site3')) ? 3 : 2)

const generatePdf = (data) => {
  window.open(`${baseUrl}/docs/get-pdfs?docTemplateName=med_notification&inputData=${encodeURIComponent(JSON.stringify(data))}`);
}

const generateSheet = (data) => {
  window.open(`${baseUrl}/sheets/get-sheets?excelTemplateName=visit_record_sheet&inputData=${encodeURIComponent(JSON.stringify(data))}`);
}

const generateDoc = (data) => {
  window.open(`${baseUrl}/docs/get-docs?docTemplateName=med_notification&inputData=${encodeURIComponent(JSON.stringify(data))}`);
}

const generateSheetPDF = (data) => {
  window.open(`${baseUrl}/sheets/get-pdf?excelTemplateName=visit_record_sheet&inputData=${encodeURIComponent(JSON.stringify(data))}`);
}

export const EventsService = {
  createNewEvent,
  getAllEvents,
  updateEvent,
  disableEvent,
  getEvent,
  deleteEvent,
  assignTransportationToEvents,
  formatDate,
  getTransportationInfo,
  generatePdf,
  generateSheet,
  generateDoc,
  generateSheetPDF,
  getTimeData,
  getByCustomer,
  site,
  // Event Recurrence
  getAllEventRecurrences,
  createEventRecurrence,
  updateEventRecurrence,
  disableEventRecurrence,
  deleteEventRecurrence,
  // New option names
  languageSupportOptions,
  labelOptions,
  activityColorOptions,
  incidentColorOptions,
  mealPlanColorOptions,
  transportationTypeOptions,
  importantDatesLegendOptions,
  importantDatesFilterOptions,
  // Legacy aliases for backward compatibility
  interpreterLevelOptions,
  colorOptions
};
