
/* 
  This is the price range component.
  It contains the following components:
  - PriceRange
*/
import { RootState } from "@/redux/slices";
import { FindAHomeContent } from "@/src/types/StaticContent/findahome.content.type";
import { handleWheelOnNumberInput, numberFieldKeyPressValidation } from "@/src/utils/commonFunctions";
import React, { useEffect, useRef, useState } from "react";
import { useFormContext } from "react-hook-form";
import { useSelector } from "react-redux";
import './PriceRange.scss';

const PriceRange: React.FC<{ staticContent: FindAHomeContent['FILTER_DATA'] }> = ({ staticContent }) => {
  const [minVal, setMinVal] = useState(1500);
  const [maxVal, setMaxVal] = useState(7000);
  const minGap = 1000;

  // // Define the currency formatter
  // const currencyFormatter = new Intl.NumberFormat("en", {
  //   style: "currency",
  //   currency: "EUR",
  //   maximumFractionDigits: 0,
  // });

  // // Handle the min change
  // const handleMinChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
  //   const value = Math.min(Number(e.target.value), maxVal - minGap);
  //   setMinVal(value);
  // }, [maxVal]);

  // // Handle the max change
  // const handleMaxChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
  //   const value = Math.max(Number(e.target.value), minVal + minGap);
  //   setMaxVal(value);
  // }, [minVal]);

  // // Get the percent
  // const getPercent = useCallback((value: number) => {
  //   return Math.round(((value - 500) / (12500 - 500)) * 100);
  // }, []);


  const [isOpen, setIsOpen] = useState(false);
  const contentRef = useRef<HTMLDivElement>(null);
  const { register } = useFormContext();
  const { filtersList } = useSelector((state: RootState) => state.property);
  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]);


  return (
    <div className="boxWrapper">
      <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">{staticContent.PRICE_RANGE}
            <span className={`fs-16 !font-fw400 !text-grey344Color`}>/{staticContent.WEEK}</span>
          </h6>
          {/* <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">2</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>
      {/* <div className="MainRangeBox">
        <div className="multi-range">
          <div className="bar-pattern" />
          <div
            className="slider-track"
            style={{
              maskImage: `linear-gradient(to right,
                transparent 0%,
                transparent ${getPercent(minVal)}%,
                black ${getPercent(minVal)}%,
                black ${getPercent(maxVal)}%,
                transparent ${getPercent(maxVal)}%,
                transparent 100%
              )`,
              WebkitMaskImage: `linear-gradient(to right,
                transparent 0%,
                transparent ${getPercent(minVal)}%,
                black ${getPercent(minVal)}%,
                black ${getPercent(maxVal)}%,
                transparent ${getPercent(maxVal)}%,
                transparent 100%
              )`,
              background: `linear-gradient(to right,
                #FF7E67 ${getPercent(minVal)}%,
                #C2F1F4 ${getPercent(maxVal)}%
              )`
            }}
          />
          <input
            type="range"
            min={500}
            max={12500}
            value={minVal}
            step={100}
            onChange={handleMinChange}
            className="thumb thumb--left"
          />
          <input
            type="range"
            min={500}
            max={12500}
            value={maxVal}
            step={100}
            onChange={handleMaxChange}
            className="thumb thumb--right"
          />
        </div>
      </div> */}
      <div
        ref={contentRef}
        className="overflow-hidden transition-[height] duration-400 ease-in-out"
        style={{ height: isOpen ? "auto" : "0px" }}
        onTransitionEnd={handleTransitionEnd}
      >
        <div className="mt-4 grid grid-cols-1 sm:grid-cols-2 gap-2.5">
          <div className="flex flex-col gap-1.5 relative">
            <label htmlFor="minimumAmount" className="font-fw500 text-size-fs14 md:text-size-fs16 text-grey344Color">{staticContent.MINIMUM_AMOUNT}</label>
            <input type="number" placeholder={staticContent.MINIMUM} 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" defaultValue={filtersList?.propertyMinimumPrice?.price} {...register('priceStart')} onWheel={handleWheelOnNumberInput} onKeyDown={numberFieldKeyPressValidation} />
          </div>
          <div className="flex flex-col gap-1.5 relative">
            <label htmlFor="maximumAmount" className="font-fw500 text-size-fs14 md:text-size-fs16 text-grey344Color">{staticContent.MAXIMUM_AMOUNT}</label>
            <input type="number" placeholder={staticContent.MAXIMUM} 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" defaultValue={filtersList?.propertyMaximumPrice?.price} {...register('priceEnd')} onWheel={handleWheelOnNumberInput} onKeyDown={numberFieldKeyPressValidation} />
          </div>
        </div>
      </div>
    </div>
  );
};

export default PriceRange;

