import React from 'react';
import OrderActionsDropdown from '../../../Dropdown';
import {
  useOrderDetailsConfirmOrder,
  useOrderStaticData,
} from '../../../../store';
import { capitalize } from '../../../../utils';

function convertTo12HourFormat(time24: any) {
  const [hours, minutes] = time24?.split(':')?.map(Number);
  const period = hours >= 12 ? 'PM' : 'AM';
  const hours12 = hours % 12 || 12; // Convert to 12-hour format
  return `${hours12}:${minutes?.toString()?.padStart(2, '0')} ${period}`;
}

function TimedServiceDropdown() {
  const [orderStaticData] = useOrderStaticData();
  const [orderData, setOrderData] = useOrderDetailsConfirmOrder();
  const timesServiceId = orderData?.order_services_detail?.timed_service_id;

  const timedServicesOptions = orderStaticData?.order_timed_services?.map(
    (option: any) => {
      const startTime = convertTo12HourFormat(option?.start_time);
      const endTime = convertTo12HourFormat(option?.end_time);
      const label = `${capitalize(
        option?.type?.replaceAll('_', ' ')
      )} (${startTime} - ${endTime})`;
      return {
        label: label,
        value: option?.id,
      };
    }
  );

  const onSelect = (event: any) => {
    const updatedServices = {
      ...orderData?.order_services_detail!,
      timed_service_id: +event,
    };
    const newData = { ...orderData, order_services_detail: updatedServices };
    setOrderData(newData);
  };
  return (
    <OrderActionsDropdown
      label="Timed Service"
      placeholder="Select Timed Service"
      options={timedServicesOptions || []}
      value={timedServicesOptions?.filter(
        (f: any) => f.value === timesServiceId
      )}
      onSelect={onSelect}
    />
  );
}

export default TimedServiceDropdown;
