"use client";
/* 
  This is the date picker item component.
  It contains the following components:
  - DatePickerItem
*/
import { DATE_FORMAT } from "@/src/utils/commonVariables";
import React, { forwardRef, useEffect, useRef } from "react";
import DatePicker from "react-datepicker";
import CustomDropdown from "../CustomDropdown/CustomDropdown";
import styles from "./DatePickerItem.module.scss";

// Define the type interface for the props
interface DatePickerItemProps {
  checkInDate: Date | null; // 'checkInDate' should be a Date | null
  setCheckInDate: React.Dispatch<React.SetStateAction<Date | null>>;
  disabled?: boolean; // 'setCheckInDate' is a state setter function
  IsDOB?: boolean;
}

const DatePickerItem: React.FC<DatePickerItemProps> = ({
  checkInDate,
  setCheckInDate,
  disabled = false,
  IsDOB = false,
}) => {
  // Define the ref for the date picker
  const datePickerRef = useRef<any>(null);
  const increaseMonthRef = useRef(null);
  const decreaseMonthRef = useRef(null);

  /**
   * Custom input component for the date picker
   * @param {string} value - The value of the date picker
   * @param {function} onClick - The function to handle the click event of the date picker
   * @param {string} className - The class name of the date picker
   * @param {ref} ref - The ref for the date picker
   */
  const ExampleCustomInput = forwardRef<
    HTMLButtonElement,
    { value: string; onClick: () => void; className: string }
  >(({ value, onClick, className }, ref) => (
    <button type="button" className={className} onClick={onClick} ref={ref}>
      {value ? (
        <span className="text-blackColor">{value}</span>
      ) : (
        <span className="text-grey667Color">Select date</span>
      )}
    </button>
  ));
  // Define the display name for the custom input component
  ExampleCustomInput.displayName = "ExampleCustomInput";

  /**
   * Handle the change event of date picker
   * @param {Date | null} date - The date to set the check in date to
   */
  const handleCheckInChange = (date: Date | null) => {
    setCheckInDate(date);
  };

  /**
   * Handle the click event of the date picker wrapper
   */
  const handleWrapperClick = () => {
    if (disabled) return;
    if (datePickerRef.current) {
      datePickerRef.current.setOpen(true);
    }
  };

  /**
   * Handle the close event of the date picker
   */
  useEffect(() => {
    if (datePickerRef.current) {
      datePickerRef.current.setOpen(false);
    }
  }, [checkInDate]);

  return (
    <div
      className={`${styles.DatePickerItemWrap
        } bg-bgColor py-[10px] px-[14px] xxl:py-[14px] xxl:px-[16px] w-full rounded-full ${disabled
          ? `cursor-default after:!w-[0px] after:!h-[0px] !max-w-max disabled-btn`
          : "cursor-pointer"
        }`}
      onClick={() => handleWrapperClick()}
    >
      <div
        className={`datePicker flex items-center justify-between gap-2.5 w-auto`}
      >
        <DatePicker
          ref={datePickerRef}
          selected={checkInDate}
          onChange={handleCheckInChange}
          dateFormat={DATE_FORMAT}
          disabled={disabled}
          minDate={!IsDOB ? new Date() : undefined}
          maxDate={IsDOB ? new Date() : undefined}
          customInput={
            <ExampleCustomInput
              value={checkInDate?.toLocaleDateString() || ""}
              onClick={() => { }}
              className={styles.input}
            />
          }
          className={`border-none outline-none bg-transparent relative text-right ${styles.input
            } ${disabled ? "cursor-default" : "cursor-pointer"}`}
          renderCustomHeader={({
            monthDate,
            decreaseMonth,
            increaseMonth,
            changeMonth,
            changeYear,
          }) => {
            increaseMonthRef.current = increaseMonth;
            decreaseMonthRef.current = decreaseMonth;

            const currentYear = new Date().getFullYear();
            const selectedYear = monthDate.getFullYear();
            const minAllowedYear = currentYear - 100;
            const maxAllowedYear = currentYear;

            let yearOptions = Array.from(
              { length: 101 },
              (_, idx) => maxAllowedYear - idx
            );

            // If selected year is outside the range, include it
            if (selectedYear < minAllowedYear) {
              yearOptions = [selectedYear, ...yearOptions];
            } else if (!yearOptions.includes(selectedYear)) {
              yearOptions.push(selectedYear);
            }

            // Sort the list just in case
            yearOptions = yearOptions.sort((a, b) => a - b);
            // Convert to { value, label } format
            const years = yearOptions.map((year) => ({
              value: year,
              label: String(year),
            }));
            const selectedYearOption = years.find(
              (y) => y.value === monthDate.getFullYear()
            );
            return (
              <>
                <div
                  style={{
                    display: "flex",
                    flexWrap: "wrap",
                    justifyContent: "space-between",
                    background: "#eee",
                    padding: "0.5em",
                  }}
                >
                  <button
                    type="button"
                    className={`group`}
                    onClick={decreaseMonth}
                  >
                    <i
                      className={`Icon IconDownArrow rotate-90 w-[15px] h-[15px] !bg-blackColor group-hover:!bg-white`}
                    ></i>
                  </button>
                  <span>
                    {monthDate.toLocaleString("default", {
                      month: "long",
                    })}{" "}
                    {!IsDOB ? monthDate.getFullYear() : ""}
                    {IsDOB && (
                      <span className="!hidden">{monthDate.getFullYear()}</span>
                    )}
                  </span>
                  <button
                    type="button"
                    className={`group`}
                    onClick={increaseMonth}
                  >
                    <i
                      className={`Icon IconDownArrow -rotate-90 w-[15px] h-[15px] !bg-blackColor group-hover:!bg-white`}
                    ></i>
                  </button>
                </div>
                {IsDOB && (
                  <>
                    <CustomDropdown
                      options={years}
                      value={selectedYearOption}
                      onChange={(e: any) => changeYear(Number(e.value))}
                      isSearchable={false}
                      isClearable={false}
                    />
                  </>
                )}
              </>
            );
          }}
        />
      </div>
    </div>
  );
};

export default DatePickerItem;
