/* 
  This is the common check box component.
  It contains the following components:
  - CommonCheckBox
*/
import { FindAHomeContent } from "@/src/types/StaticContent/findahome.content.type";
import { handleWheelOnNumberInput } from "@/src/utils/commonFunctions";
import { REGEX } from "@/src/utils/commonVariables";
import React, { useEffect, useRef, useState } from "react";
import { useFormContext } from "react-hook-form";

// Define the props for the CommonCheckBox item
interface CommonItem {
  amenitiesId?: string;
  title: string;
  slug: string
}

// Define the props for the CommonCheckBox list and title
interface CommonCheckBoxProps {
  CommonDetails: {
    Title: string; // Title is inside the object
    key: string;
    items: CommonItem[]; // Array of checkboxes
  };
  staticContent?: FindAHomeContent['FILTER_DATA']
}

const CommonCheckBox: React.FC<CommonCheckBoxProps> = ({ CommonDetails, staticContent }) => {

  const [isOpen, setIsOpen] = useState(false);
  const contentRef = useRef<HTMLDivElement>(null);
  const { register, watch, setValue } = useFormContext();
  const toggleAccordion = () => {
    if (!contentRef.current) return;

    const el = contentRef.current;

    if (isOpen) {
      // Collapse
      const currentHeight = el.scrollHeight;
      el.style.height = `${currentHeight}px`; // Set current height
      requestAnimationFrame(() => {
        el.style.height = "0px"; // Then animate to 0
      });
    } else {
      // Expand
      el.style.height = el.scrollHeight + "px"; // Set to full height
    }

    setIsOpen(!isOpen);
  };

  const handleTransitionEnd = () => {
    if (!contentRef.current) return;

    if (isOpen) {
      // After expanding, remove fixed height
      contentRef.current.style.height = "auto";
    }
  };

  useEffect(() => {
    // Recalculate height on resize
    const handleResize = () => {
      if (isOpen && contentRef.current) {
        contentRef.current.style.height = contentRef.current.scrollHeight + "px";
      }
    };
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, [isOpen]);

  /**
   * Handles changes to a number input field.
   * Validates the input value against the SPEED regex and updates the 'minInternetSpeed' field
   * if the value matches.
   * 
   * @param e - The change event triggered on input field change.
   */
  const handleNumberFieldChange = (
    e: React.ChangeEvent<HTMLInputElement>, // Event triggered on input change
  ) => {
    const inputValue = e.target.value; // Get the entered value
    // Prevent input longer than 4 digits
    if (inputValue.length > 4) return;
    if (REGEX.SPEED.test(inputValue)) {
      setValue('minInternetSpeed', inputValue); // Update the field value if it matches the regex
    }
  };

  /**
   * Prevents non-digit key presses in input fields, allowing only digits and certain control keys.
   * 
   * @param e - The keyboard event triggered on key press.
   * Prevents default behavior if the key pressed is not a digit or a control key.
   */
  const preventNonDigitKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
    const allowedKeys = ['Backspace', 'Delete', 'ArrowLeft', 'ArrowRight', 'Tab'];
    const isDigit = /^[0-9]$/.test(e.key);

    if (!isDigit && !allowedKeys.includes(e.key)) {
      e.preventDefault();
    }
  };

  return (
    // Mainbox wrapper
    <div className="boxWrapper">
      {/* Title wrapper */}
      <div className={`titleWrapper justify-between items-center flex cursor-pointer gap-2 !mb-0`} onClick={toggleAccordion}>
        <div className="flex items-center gap-2.5 w-fit">
          <h6 className="w-fit !m-0 !font-fw600 md:!text-size-fs20">{CommonDetails.Title}</h6>
          {watch(CommonDetails.key)?.length ? <span className="rounded-full bg-secondaryColor text-white text-size-fs16 font-fw600 h-6 w-fit flex justify-center items-center p-1 min-w-6">{watch(CommonDetails.key)?.length}</span> : ''}
        </div>
        <i className={`Icon IconDownArrow !h-4 md:!h-5 !w-4 md:!w-5 ${isOpen ? "rotate-180 !bg-secondaryColor" : "rotate-0 !bg-grey667Color"}`}></i>
      </div>
      {/* Loop for using multiple boxes */}
      <div
        ref={contentRef}
        className="overflow-hidden transition-[height] duration-400 ease-in-out"
        style={{ height: isOpen ? "auto" : "0px" }}
        onTransitionEnd={handleTransitionEnd}
      >
        <div className="boxGrid !gap-x-2.5 !gap-y-2.5 xxl:!gap-y-4 mt-4">
          {CommonDetails.items?.map((items: CommonItem, i: number) => (
            <div key={i}>
              <label className="fs-14 CheckBoxBG CommonCheckbox cursor-pointer" htmlFor={items.slug}>
                <input type="checkbox" value={items?.amenitiesId ? items?.amenitiesId : items?.slug} id={items.slug} {...register(CommonDetails.key)} />
                <span>{items.title}</span>
              </label>
              {/* Condition for showing tooltip if the json have tooltip data  */}
              {/* {items.TooltipTitle && items.TooltipDescription ? (
              <div className="tooltipMainBox">
                <span className="tooltipSpan">
                  <i className="Icon IconInfo"></i>
                </span>
                <div className="hiddenTooltip">
                  <p><b>{items.TooltipTitle}</b></p>
                  <p>{items.TooltipDescription}</p>
                </div>
              </div>
            ) : null} */}
            </div>
          ))}
        </div>
        {CommonDetails?.Title === "Workspace" ? (
          <div className="flex flex-col gap-1.5 relative mt-4">
            <label htmlFor="minimumAmount" className="font-fw500 text-size-fs14 md:text-size-fs16 text-grey344Color">{staticContent?.MINIMUM_INTERNET_SPEED}</label>
            <input type="text" inputMode="numeric" maxLength={4} placeholder="50 Mbps" className="px-3.5 py-2.4 rounded-[200px] bg-white text-grey344Color text-size-fs14 md:text-size-fs16 border-0 outline-0 h-[44px] w-full"
              {...register('minInternetSpeed', { onChange: (e) => handleNumberFieldChange(e) })} onWheel={handleWheelOnNumberInput} onKeyDown={preventNonDigitKeyPress} />
          </div>
        ) : ''}
      </div>
    </div>
  );
};


export default CommonCheckBox;
