"use client";

import type React from "react";
import { useState, useRef, useEffect } from "react";
import { ChevronDown, ChevronUp } from "lucide-react";
import { usePathname } from "next/navigation";
import { useGetUserProfile } from "@/src/utils/hooks/useGetUserProfile";
import SectionSkeleton from "./Loading";

interface CustomSelectOption {
  label: string;
  value: string;
  subcategories?: { label: string; value: string }[];
}

interface CustomSelectProps {
  value: string; // now this is label, not value
  subValue?: string;
  onChange: (label: string, subValue?: string) => void; // label used here too
  options: CustomSelectOption[];
  placeholder?: string;
  label?: string;
  icon?: React.ReactNode;
  weight?: number;
  disabled?: boolean;
}

const CustomSelect: React.FC<CustomSelectProps> = ({
  value,
  subValue,
  onChange,
  options,
  placeholder = "Select an option",
  label,
  icon,
  weight,
  disabled,
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const [displayText, setDisplayText] = useState(placeholder);
  const [selectedSubcategory, setSelectedSubcategory] = useState<
    string | undefined
  >(subValue);
  const [showSubcategories, setShowSubcategories] = useState(false);
  const [currentCategory, setCurrentCategory] = useState<string | null>(null);
  const [existingCategory, setExistingCategory] = useState<string | null>();
  const [searchTerm, setSearchTerm] = useState("");
  const selectRef = useRef<HTMLDivElement>(null);
  const pathname = usePathname();

  useEffect(() => {
    if (!Array.isArray(options)) return;

    const selected = options.find((option) => option.label === value);
    if (selected) {
      setDisplayText(selected.label);

      if (selected.subcategories && selected.subcategories.length > 0) {
        setCurrentCategory(selected.label);
      } else {
        setShowSubcategories(false);
        setCurrentCategory(null);
      }
    } else {
      setDisplayText(placeholder);
      setShowSubcategories(false);
      setCurrentCategory(null);
    }

    setSelectedSubcategory(subValue);
  }, [value, subValue, options, placeholder]);

  // Close dropdown when clicking outside
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (
        selectRef.current &&
        !selectRef.current.contains(event.target as Node)
      ) {
        setIsOpen(false);
        setShowSubcategories(false);
        
      }
    }

    document.addEventListener("mousedown", handleClickOutside, {
      capture: true,
    });

    return () => {
      document.removeEventListener("mousedown", handleClickOutside, {
        capture: true,
      });
    };
  }, []);

  const { data: profile, isLoading } = useGetUserProfile();

  useEffect(() => {
    const gottenReligion = profile?.payload?.about_me?.religion;
    if (gottenReligion && Array.isArray(gottenReligion)) {
      const retrievedDenomination = gottenReligion.map(
        (item) => item?.denomination
      );
      setExistingCategory(retrievedDenomination[0] as string);
    }
  }, [profile]);

  useEffect(() => {
    if (subValue !== selectedSubcategory) {
      setSelectedSubcategory(subValue);
    }
  }, [subValue]);

  const handleSelect = (optionLabel: string) => {
    onChange(optionLabel, undefined);
    setDisplayText(optionLabel);
    setSelectedSubcategory(undefined);
    setIsOpen(false);
    setSearchTerm(""); // reset search

    const selectedOption = options.find((opt) => opt.label === optionLabel);

    if (selectedOption?.subcategories?.length) {
      setCurrentCategory(optionLabel);
      setShowSubcategories(true);
      setIsOpen(true); // keep open
    } else {
      setCurrentCategory(null);
      setShowSubcategories(false);
      setIsOpen(false); // close if no subcategories
    }
  };

  const handleHeaderClick = (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setShowSubcategories(false);
    setIsOpen(false);
  };

  const handleSubcategorySelect = (subcategoryValue: string) => {
    setSelectedSubcategory(subcategoryValue);
    if (currentCategory) {
      const category = options.find(
        (option) => option.label === currentCategory
      );
      if (category) {
        onChange(category.label, subcategoryValue);
      }
    }

    // setShowSubcategories(false);
    // setIsOpen(false);
  };

  const toggleDropdown = (e: React.MouseEvent) => {
    e.stopPropagation();
    if (disabled) return;

    if (isOpen) {
      setIsOpen(false);
      setShowSubcategories(false);
    } else {
      setIsOpen(true);
      setShowSubcategories(false);
    }
  };

  // Filter options based on search term
  const filteredOptions = options.filter((option) =>
    option.label.toLowerCase().includes(searchTerm.toLowerCase())
  );

  useEffect(() => {
    if(!isOpen){
      setSearchTerm("")
    }
  }, [isOpen])

  return isLoading ? (
    <SectionSkeleton />
  ) : (
    <div
      className={`flex flex-col w-full gap-y-1 text-black font-light ${
        pathname.includes("profile-setup") ? "font-poppins" : "font-inter"
      }`}
      ref={selectRef}
    >
      {label && (
        <label
          className="text-[11px] font-semibold flex items-center"
          style={{ fontWeight: weight ? weight : 400 }}
        >
          {icon && <span className="mr-2">{icon}</span>}
          <span>{label}</span>
        </label>
      )}

      <div className="relative w-full">
        {/* Select Trigger Button */}
        <button
          type="button"
          className={`flex items-center justify-between gap-2 rounded-md border border-input px-3 py-2 text-[10px] w-full ${
            disabled ? "bg-[#D9D9D9]" : "bg-[#F9F9F9] cursor-pointer"
          } h-9 shadow-xs`}
          onClick={disabled ? undefined : toggleDropdown}
          aria-haspopup="listbox"
          aria-expanded={isOpen}
          disabled={disabled}
        >
          <span className="truncate">{displayText}</span>
          {isOpen ? (
            <ChevronUp className="size-4 opacity-50" />
          ) : (
            <ChevronDown className="size-4 opacity-50" />
          )}
        </button>

        {/* Dropdown Menu with Search */}
        {!disabled && isOpen && (
          <div
            className="absolute z-50 w-full mt-1 bg-white border rounded-md shadow-lg max-h-60 overflow-auto"
            role="listbox"
          >
            {/* Search Input */}
            <div className="sticky top-0 bg-white p-2 border-b">
              <input
                type="text"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                placeholder="Search..."
                className="w-full px-2 py-1 text-[10px] border rounded"
              />
            </div>

            {filteredOptions.length > 0 ? (
              filteredOptions.map((option) => (
                <div
                  key={option.value}
                  className={`px-3 py-2 text-sm cursor-pointer hover:bg-gray-100 text-[9px] ${
                    option.label === value ? "bg-gray-100" : ""
                  }`}
                  role="option"
                  aria-selected={option.label === value}
                  onClick={() => handleSelect(option.label)}
                >
                  {option.label}
                </div>
              ))
            ) : (
              <div className="px-3 py-2 text-[9px] text-gray-400">
                No results found
              </div>
            )}
          </div>
        )}

        {/* Subcategories Panel */}
        {!disabled && showSubcategories && currentCategory && (
          <div className="absolute z-50 w-full mt-1 bg-[#F9F9F9] border rounded-md shadow-lg max-h-60 overflow-auto p-4">
            <button
              type="button"
              className="font-light mb-4 text-[12px] cursor-pointer w-full text-left"
              onClick={handleHeaderClick}
            >
              {options.find((opt) => opt.label === currentCategory)?.label}
            </button>
            <div className="flex flex-wrap gap-y-3">
              {options
                .find((opt) => opt.label === currentCategory)
                ?.subcategories?.map((subcat) => (
                  <label
                    key={subcat.value}
                    className="flex items-center cursor-pointer text-[10px] mr-3"
                  >
                    <input
                      type="radio"
                      name="subcategory"
                      value={subcat.value}
                      // checked={
                      //   selectedSubcategory === subcat.value ||
                      //   subcat.value === existingCategory
                      // }
                      checked={selectedSubcategory === subcat.value}
                      onChange={() => handleSubcategorySelect(subcat.value)}
                      className="accent-gray-400 w-4 h-4 mr-1"
                    />
                    {subcat.label}
                  </label>
                ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default CustomSelect;
