import React from 'react';
import { useOrderDetails, useOrderStaticData } from '../../../store';
import {
  dropdownStyles,
  Label,
  SelectDropdown,
} from '@bjsdistribution/dms-component-library';
import styled from 'styled-components';
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] = useOrderDetails();

  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 onChange = (event: any) => {
    const updatedServices = {
      ...orderData?.order_services_detail!,
      timed_service_id: event.value,
    };
    const newData = { ...orderData, order_services_detail: updatedServices };
    setOrderData(newData);
  };

  const isDisabled = true;

  return (
    <Container>
      <Label label="Timed Service" />
      <StyledSelectDropdown
        styles={{
          ...dropdownStyles,
          control: (styles: any) => ({
            ...styles,
            minWidth: 'max-content',
          }),
        }}
        placeholder="Select Timed Service"
        options={timedServicesOptions || []}
        value={timedServicesOptions?.filter(
          (f: any) => f.value === timesServiceId
        )}
        inputId="timedServiceDropdown"
        onChange={onChange}
        // isDisabled={isDisabled}
        className={isDisabled ? 'disabled' : ''}
      />
    </Container>
  );
}

const Container = styled.div`
  display: flex;
  flex-direction: column;
  gap: 6px;
  flex: 1;
`;

const StyledSelectDropdown = styled(SelectDropdown)`
  &.disabled {
    pointer-events: none;
    opacity: 0.7;
  }
`;

export default TimedServiceDropdown;
