import { FindAHomeContent } from '@/src/types/StaticContent/findahome.content.type';
import { useEffect, useRef, useState } from 'react';
import { useFormContext } from 'react-hook-form';

export default function RoomCounterGroup({ counts, setCounts, staticContent }: { counts: any, setCounts: any, staticContent: FindAHomeContent['FILTER_DATA'] }) {
  const [totalCount, setTotalCount] = useState(0);
  const { register, setValue } = useFormContext();

  /**
   * Increases the count of a specified type by 1 and updates the form value.
   * 
   * @param type - The type of count to increment (e.g., 'bedroomCount', 'bedCount', 'bathroomCount').
   */
  const increment = (type: typeof counts) => {
    setCounts((prev) => {
      const updated = { ...prev, [type]: prev[type] + 1 };
      setValue(type, `${updated[type]}+`);
      return updated;
    });
  };

  /**
   * Decreases the count of a specified type by 1, ensuring it doesn't go below 0.
   * Updates the form value for the given type with the new count followed by a '+' if greater than 0,
   * otherwise sets it to "0".
   * 
   * @param {keyof typeof counts} type - The type of count to decrement (e.g., bedroomCount, bedCount, bathroomCount).
   */
  const decrement = (type: typeof counts) => {
    setCounts((prev) => {
      const newValue = prev[type] > 0 ? prev[type] - 1 : 0;
      const updated = { ...prev, [type]: newValue };
      setValue(type, newValue > 0 ? `${newValue}+` : "0");
      return updated;
    });
  };

  const [isOpen, setIsOpen] = useState(false);
  const contentRef = useRef<HTMLDivElement>(null);
  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";
    }
  };

  /* Calculate total count */
  useEffect(() => {
    setTotalCount(Object.values(counts).filter((count: number) => count > 0).length)
  }, [counts])

  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]);

  const renderCounter = (label: string, type: typeof counts) => (
    <div key={type} className='flex justify-between items-center gap-2.5 flex-wrap w-full !bg-[#FFFFFF80] rounded-[10px] p-2'>
      <p className='fs-16 !font-fw500 !mb-0'>{label}</p>
      <div className='max-w-[130px] xsm:max-w-[100%] rounded-full flex justify-between items-center gap-1.5 xsm:gap-2.5'>
        <button
          type='button'
          onClick={() => decrement(type)}
          className={`${counts[type] < 1 && "!bg-[#E0E0E0] !cursor-not-allowed"} bg-primaryColor transition-all duration-200 hover:bg-secondaryColor shrink-0 !p-0 rounded-full flex items-center justify-center w-[30px] xsm:w-[45px] h-[20px] cursor-pointer`}
        >
          <i className='Icon IconMinus !w-[12px] !h-[12px] !bg-whiteColor'></i>
        </button>
        <input
          type="text"  // changed from "number" to "text"
          readOnly
          className="text-center text-black28 w-[20px] xsm:w-14"
          value={`${counts?.[type] < 1 ? 'Any' : counts?.[type] + '+'}`}  // adds + symbol safely value={(counts?.[type] ?? 0) + "+"}
          {...register(type)}
        />
        <button
          type='button'
          onClick={() => increment(type)}
          className='bg-primaryColor transition-all duration-200 hover:bg-secondaryColor shrink-0 !p-0 rounded-full flex items-center justify-center w-[30px] xsm:w-[45px] h-[20px] cursor-pointer'
        >
          <i className='Icon IconPlus !w-[12px] !h-[12px] !bg-whiteColor'></i>
        </button>
      </div>
    </div>
  );

  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.ROOMS_AND_BEDS}</h6>
          {totalCount > 0 ? <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">{totalCount}</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
        ref={contentRef}
        className="overflow-hidden transition-[height] duration-400 ease-in-out"
        style={{ height: isOpen ? "auto" : "0px" }}
        onTransitionEnd={handleTransitionEnd}
      >
        <div className="space-y-4 mt-4">
          {renderCounter('Bedrooms', 'bedroomCount')}
          {renderCounter('Beds', 'bedCount')}
          {renderCounter('Bathrooms', 'bathroomCount')}
        </div>
      </div>
    </div>
  );
}
