/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { useState, useEffect } from "react";
import moment from "moment-timezone";
import { useAppSelector } from "@/Redux/Hooks";
import { useDispatch } from "react-redux";
import { saveStepData } from "@/Redux/Reducers/CreateOrderSlice";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import { getPickupTimeSlots, TimeSlot } from "../../utlits/PickupTimes";
import { isServiceAvailable } from "../../../lib/Helper";

// Same Day
// Booking Time - 00:00 to 12:00
// Pickup Time - 8:00 to 13:00

// Express
// Booking Time - 00:00 to 16:00
// Pickup Time - 8:00 to 18:00

// Next day
// Booking Time - 00:00 to 19:00
// Pickup Time - 8:00 to 21:00

const PickupForm = ({ serviceType, errors, setErrors, selectedDate, setSelectedDate, selectedTime, setSelectedTime, disabled }: any) => {
  const completeOrder: any = useAppSelector((state) => state.createOrder);
  const dispatch = useDispatch();
  const timezone = process.env.TZ || "UTC";
  const [isCustomDate, setIsCustomDate] = useState<boolean>(false);
  const [showDatePicker, setShowDatePicker] = useState<boolean>(false);
  const [showDateError, setShowDateError] = useState<boolean>(false);
  const [showTimeError, setShowTimeError] = useState<boolean>(false);
  const [savedData, setSavedData] = useState<{
    date: string | null;
    time: number;
  }>({
    date: completeOrder?.makePayment?.date ?? null,
    time: completeOrder?.makePayment?.time ?? "",
  });

  // Only dispatch when the selected date or time is different from the saved data
  useEffect(() => {
    if (selectedDate !== savedData.date || selectedTime !== savedData.time) {
      const updatedCompleteOrder: any = {
        ...completeOrder?.step3,
        makePayment: {
          date: selectedDate,
          time: selectedTime,
        },
      };

      // Dispatch to update Redux store
      dispatch(saveStepData({ step: "step3", data: updatedCompleteOrder }));

      // Update the saved data to reflect the new values
      setSavedData({
        date: selectedDate,
        time: selectedTime,
      });
    }
  }, [selectedDate, selectedTime, completeOrder, dispatch, savedData]);
  function getDayAfterTomorrow() {
    return moment().tz(timezone).add(2, "days").format("YYYY-MM-DD");
  }
  const handleCheckboxChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const { id, checked } = event.target;

    // Uncheck all checkboxes before setting the new state
    if (checked) {
      if (id === "check13") {
        setSelectedDate(moment().format("YYYY-MM-DD"));
        setErrors({ ...errors, pickupDate: "" })
        setIsCustomDate(false);
        setShowDatePicker(false);
      } else if (id === "check14") {
        setSelectedDate(moment().add(1, "days").format("YYYY-MM-DD"));
        setErrors({ ...errors, pickupDate: "" })
        setIsCustomDate(false);
        setShowDatePicker(false);
      } else if (id === "check15") {
        setErrors({ ...errors, pickupDate: "" })
        setIsCustomDate(true);
        setShowDatePicker(true);
      }

      // Uncheck all other checkboxes
      if (id !== "check13")
        document.getElementById("check13")?.setAttribute("checked", "false");
      if (id !== "check14")
        document.getElementById("check14")?.setAttribute("checked", "false");
      if (id !== "check15")
        document.getElementById("check15")?.setAttribute("checked", "false");
    } else {
      // If unchecking any checkbox, reset the date and time
      setSelectedDate(null);
      setIsCustomDate(false);
      setShowDatePicker(false);
    }
  };

  const handleDateChange = (date: Date | null) => {
    if (date) {
      setSelectedDate(moment(date).format("YYYY-MM-DD"));
      setErrors({ ...errors, pickupDate: "" })
      setShowDatePicker(false);
      setShowDateError(false);
    }
  };

  const handleTimeChange = (time: number) => {
    setSelectedTime(time);
    setErrors({ ...errors, pickupTime: "" })
    setShowTimeError(false);
  };

  const timeSlots: TimeSlot[] = getPickupTimeSlots(serviceType, selectedDate);

  return (
    <>
      <div className="col-lg-6">
        <h5 className="font-15 pb-1 mb-0 mt-2">
          Pickup Date <span className="text-danger">*</span>
        </h5>
        {showDateError && (
          <p className="text-danger mb-2 font-12">Please select a pickup date</p>
        )}
        <div className="step1-package px-2 pe-0">
          {isServiceAvailable(serviceType?.name || "") ? (
            <div className="form-check interest-check">
              <input
                className="form-check-input"
                type="checkbox"
                id="check13"
                disabled={disabled}
                onChange={handleCheckboxChange}
                checked={selectedDate === moment().format("YYYY-MM-DD")} // Check if "Today" is selected
              />
              <label
                className="form-check-label shadow-xl rounded-xl"
                htmlFor="check13"
              >
                Today
              </label>
              <i className="fa fa-check-circle color-white font-18" />
              {/* <i className="fa fa-clock font-17 color-yellow2" /> */}
              <i className="ri-time-line font-17 color-yellow2" />
            </div>
          ) : ''}
          <div className="form-check interest-check">
            <input
              className="form-check-input"
              type="checkbox"
              id="check14"
              disabled={disabled}
              onChange={handleCheckboxChange}
              checked={
                selectedDate === moment().add(1, "days").format("YYYY-MM-DD")
              } // Check if "Tomorrow" is selected
            />
            <label
              className="form-check-label shadow-xl rounded-xl"
              htmlFor="check14"
            >
              Tomorrow
            </label>
            <i className="fa fa-check-circle color-white font-18" />
            {/* <i className="fa fa-calendar font-17 color-yellow2" /> */}
            <i className="ri-calendar-line font-17 color-yellow2" />
          </div>
          <div className="form-check interest-check">
            <input
              className="form-check-input"
              type="checkbox"
              id="check15"
              disabled={disabled}
              onChange={handleCheckboxChange}
              checked={isCustomDate} // Check if "Custom" is selected
            />
            <label
              className="form-check-label shadow-xl rounded-xl"
              htmlFor="check15"
            >
              Custom
            </label>
            <i className="fa fa-check-circle color-white font-18" />
            {/* <i className="fa fa-calendar font-17 color-yellow2" /> */}
            <i className="ri-calendar-line font-17 color-yellow2" />
          </div>
          {errors.pickupDate && (
            <div className="text-danger px-2 error-box mb-2">{errors.pickupDate}</div>
          )}
        </div>

        {/* Selected Date Display */}
        {selectedDate && (
          <div className="selected-date-display mb-2">
            <p className="mb-0 font-14">
              Selected Date:{" "}
              <span className="text-danger fw-bold">
                {moment(selectedDate).format("MMMM D, YYYY")}
              </span>
            </p>
          </div>
        )}

        {/* Date Input Popup */}
        {showDatePicker && (
          <div
            className="date-picker-popup"
            style={{
              position: "fixed",
              top: "50%",
              left: "50%",
              transform: "translate(-50%, -50%)",
              zIndex: 1000,
              backgroundColor: "white",
              boxShadow: "0 2px 10px rgba(0,0,0,0.1)",
              borderRadius: "8px",
              padding: "20px",
            }}
          >
            <div className="d-flex justify-content-between align-items-center mb-3">
              <h6 className="mb-0">Select Pickup Date</h6>
              <button
                className="btn-close"
                onClick={() => setShowDatePicker(false)}
                style={{ cursor: "pointer" }}
              />
            </div>
            <DatePicker
              selected={selectedDate ? new Date(selectedDate) : null}
              onChange={handleDateChange}
              inline
              minDate={new Date(getDayAfterTomorrow())}
              calendarClassName="custom-calendar"
            />
          </div>
        )}
      </div>
      <div className="col-lg-6">
        {/* Time of Day Selection */}
        <div className="d-float-center justify-content-between time-hrs">
          <h5 className="font-15 pb-1 mb-0 mt-2">
            Pickup Time <span className="text-danger">*</span>
          </h5>
          {showTimeError && (
            <p className="text-danger mb-2 font-12">
              Please select a pickup time
            </p>
          )}
          {/* <p className="mb-0 time-hrs font-12 text-danger fw-bold">
            {selectedTime === 1
              ? `09:00 AM - 12:00 PM`
              : selectedTime === 2
                ? `04:00 PM - 06:00 PM`
                : selectedTime === 3
                  ? `04:00 PM - 07:00 PM`
                  : ``}
          </p> */}
        </div>
        <div className="step1-package px-2 pe-0">
          {timeSlots.map((slot) => {
            const timeLabel = slot?.mainLabel;
            const iconClass = slot?.icon;
            return (
              <div className="form-check interest-check" key={slot.value}>
                <input
                  className="form-check-input"
                  type="radio"
                  id={`check-time-${slot.value}`}
                  name="time"
                  disabled={disabled}
                  onChange={() => handleTimeChange(slot.value)}
                  checked={selectedTime === slot.value}
                />
                <label
                  className="form-check-label shadow-xl rounded-xl"
                  htmlFor={`check-time-${slot.value}`}
                >
                  {timeLabel}
                  <i className={`${iconClass} font-17 color-yellow2`} />
                </label>
              </div>
            );
          })}
          {errors.pickupTime && (
            <div className="text-danger px-2 error-box mb-2">{errors.pickupTime}</div>
          )}
        </div>
        {selectedDate && (
          <div className="selected-date-display mb-2">
            <p className="mb-0 font-14">
              Selected Time Slot:{" "}
              <span className="text-danger fw-bold">
                {selectedTime === 1
                  ? `09:00 AM - 12:00 PM`
                  : selectedTime === 2
                    ? `04:00 PM - 06:00 PM`
                    : selectedTime === 3
                      ? `04:00 PM - 07:00 PM`
                      : ``}              </span>
            </p>
          </div>
        )}
      </div>
    </>
  );
};

export default PickupForm;
