"use client";
/* 
  This is the property type component.
  It contains the following components:
  - PropertyType
*/
import { RootState } from "@/redux/slices";
import { PropertyTypes } from "@/redux/types/propertyTypes";
import { FindAHomeContent } from "@/src/types/StaticContent/findahome.content.type";
import Image from "next/image";
import React, { useEffect, useRef, useState } from "react";
import { Controller, useFormContext } from "react-hook-form";
import { useSelector } from "react-redux";
import styles from "./PropertyType.module.scss";


const PropertyType: React.FC<{ staticContent: FindAHomeContent['FILTER_DATA'] }> = ({ staticContent }) => {
  const [selectedIndices, setSelectedIndices] = useState<number[]>([]);
  const [isOpen, setIsOpen] = useState(true);
  const contentRef = useRef<HTMLDivElement>(null);
  const { filtersList } = useSelector((state: RootState) => state.property);
  const { control, watch } = 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]);
  const toggleSelection = (index: number) => {
    setSelectedIndices((prev) =>
      prev.includes(index)
        ? prev.filter((i) => i !== index)
        : [...prev, index]
    );
  };

  useEffect(() => {
    setIsOpen(true);
  }, [filtersList])

  return (
    <>
      {/* Property Type list 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">{staticContent?.PROPERTY_TYPE}</h6>
            {watch('propertyType').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('propertyType').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 code for multiple boxes of property Type */}
        <div
          ref={contentRef}
          className="overflow-hidden transition-[height] duration-400 ease-in-out"
          style={{ height: isOpen ? "auto" : "0px" }}
          onTransitionEnd={handleTransitionEnd}
        >
          <div className={`grid !grid-cols-2 gap-y-3 gap-x-3 mt-4`}>
            {filtersList?.propertyTypes?.map((item: PropertyTypes, i: number) => {

              return (
                <Controller
                  name="propertyType"
                  control={control}
                  key={i}
                  render={({ field: { onChange, value } }) => (
                    <div
                      key={i}
                      className={`relative text-center rounded-lg p-3 flex flex-col items-center cursor-pointer transition duration-300 ease-in-out ${watch('propertyType').includes(item?.propertyTypeId) ? styles.active : ''} ${styles.propertyBox}`}
                      onClick={() => {
                        onChange(
                          value.includes(item?.propertyTypeId)
                            ? value.filter((propertyTypeId: string) => propertyTypeId !== item?.propertyTypeId)
                            : [...value, item?.propertyTypeId],
                        );
                      }}
                    >
                      {/* Checkbox icon at top right */}
                      <div className="absolute top-2 right-2">
                        <div
                          className={`w-5 h-5 rounded-[5px] flex items-center justify-center ${watch('propertyType').includes(item?.propertyTypeId) ? 'bg-primaryColor' : 'bg-bgColor'
                            }`}
                        >
                          {watch('propertyType').includes(item?.propertyTypeId) && (
                            <svg
                              className="w-3.5 h-3.5 text-white"
                              fill="none"
                              stroke="currentColor"
                              strokeWidth="2"
                              viewBox="0 0 24 24"
                            >
                              <path d="M5 13l4 4L19 7" />
                            </svg>
                          )}
                        </div>
                      </div>

                      {/* Icon */}
                      <div className={`w-10 h-10 ${styles.propertyIcon}`}>
                        <Image
                          src={watch('propertyType').includes(item?.propertyTypeId) ? item.selectedIcon : item.icon}
                          alt="icon"
                          width={40}
                          height={40}
                        />
                      </div>

                      {/* Title */}
                      <p className={`fs-16 mt-2 mb-0 transition duration-300 ease-in-out ${watch('propertyType').includes(item?.propertyTypeId) ? 'text-white' : 'text-grey344Color'}`}>
                        {item.title}
                      </p>
                    </div>
                  )}
                />
              );
            })}
          </div>
        </div>
      </div>
    </>
  );
};

export default PropertyType;
