import ProRatioGroups from "components/ProRatioGroups/ProRatioGroups.tsx";
import ProInputCard from "components/ProInputCard/ProInputCard.tsx";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { updateEstimateTime, selectCart } from "features/order/orderSlice.ts";
import { message } from "antd";
import { BottomSheet } from "pages/cart/components/timeEstimate/BottomSheet.tsx";
import { useAppDispatch, useAppSelector } from "redux/hooks.ts";
import useBreakPoint from "hooks/useBreakPoint.ts";
import { Dialog } from "pages/cart/components/timeEstimate/Dialog.tsx";

export default function TimeEstimateCard() {
  const { t } = useTranslation();
  const dispatch = useAppDispatch();
  const { estimateTimeDate } = useAppSelector(selectCart);
  const { isDesktop } = useBreakPoint();
  const [estimateWay, setEstimateWay] = useState("now");
  const [isEstimateTimeOpen, setIsEstimateTimeOpen] = useState(false);

  const handleEstimateTimeSave = (date: Date, time: string) => {
    dispatch(updateEstimateTime({ date, time }));
    message.success(t("cart.estimateTime") + " " + t("updatedSuccessfully"));
  };

  const handleEstimateTimeClose = () => {
    setIsEstimateTimeOpen(false);
  };

  return (
    <>
      <ProInputCard title={t("cart.estimateTime")}>
        <ProRatioGroups
          options={[
            { label: t("cart.now"), value: "now", price: "" },
            { label: t("cart.later"), value: "later", price: "" },
          ]}
          value={estimateWay}
          onRatioClick={(value) => {
            if (value === "now") {
              setEstimateWay(value);
              handleEstimateTimeSave(new Date(), "now");
            } else {
              setEstimateWay(value);
              setIsEstimateTimeOpen(true);
            }
          }}
        />
      </ProInputCard>
      {isDesktop ? (
        <Dialog
          isOpen={isEstimateTimeOpen}
          onClose={handleEstimateTimeClose}
          initialDate={estimateTimeDate}
          onSave={handleEstimateTimeSave}
        />
      ) : (
        <BottomSheet
          isOpen={isEstimateTimeOpen}
          onClose={handleEstimateTimeClose}
          initialDate={estimateTimeDate}
          onSave={handleEstimateTimeSave}
        />
      )}
    </>
  );
}
