import React from "react";
import { Dropdown as SelectDropdown } from "@/modules/ui/select-dropdown";
import { useProductStore } from "@/zustand/productStore";
import { useEstimatedDate } from "@/lib/hooks/useEstimatedDate";
import {
  DeliveryTimeModel,
  HolidayModel,
  ProductTurnaroundTimeModel,
} from "@/lib/types/models";

export default function ProductQuantityOption({
  turnaroundTimeData,
  deliveryTimeList,
  holidaysList,
}: {
  deliveryTimeList: DeliveryTimeModel[];
  holidaysList: HolidayModel[];
  turnaroundTimeData: ProductTurnaroundTimeModel[];
}) {
  const { getEstimatedDate } = useEstimatedDate(deliveryTimeList, holidaysList);
  const {
    quantityOption,
    selectQuantityAndEstimatedDate,
    setQuantityAndEstimatedDate,
    turnaroundTimeOptionData,
  } = useProductStore();

  const handleQuantityOptionChange = async (value: number) => {
    try {
      const newData = {
        ...selectQuantityAndEstimatedDate,
      };

      const newPrice = quantityOption.find((resp) => resp.quantity == value);
      newData.quantity = value.toString();
      newData["percentage"] = newPrice?.percentage?.toString() || "";
      newData.productOptionPrice = (
        Number(newPrice?.price)
      ).toString();

      const activeTurnaroundData =
        turnaroundTimeOptionData?.length > 0
          ? turnaroundTimeOptionData
          : turnaroundTimeData;

      const timeRange = activeTurnaroundData.find(
        (element) =>
          value >= Number(element.min) && value <= Number(element.max)
      );
      const tt = timeRange?.turnaroundTimes?.[0];
      if (tt) {
        const estimatedTime = await getEstimatedDate(tt);
        const date = new Date(estimatedTime);
        newData.turnaroundTime = tt.name;
        newData.estimateCompleteDate = date.toLocaleDateString("en-us", {
          weekday: "long",
          year: "numeric",
          month: "short",
          day: "numeric",
          timeZone: "UTC",
        });
      }
      setQuantityAndEstimatedDate(newData);
    } catch (error) {
      console.error("Error processing product data:", error);
    }
  };
  return (
    <SelectDropdown
      disabled={false}
      isSearchable={false}
      options={quantityOption || []}
      labelText={"Quantity"}
      label="quantity"
      value="quantity"
      isLabelMultiple={true}
      selected={Number(selectQuantityAndEstimatedDate?.quantity) || 0}
      onChange={(e) => e && handleQuantityOptionChange(e.quantity)}
    />
  );
}
