import { useState, useEffect } from "react";
import SafeHtmlRenderer from "../SafeHtmlRenderer";
import { useRouter } from "next/navigation";
import axios from "axios";
import { BASE_URL } from "@/Constant";

export default function HeroAccreditationBody({ data }: any) {
  const router = useRouter();
  const [selected, setSelected] = useState("hs-radio-group-1");
  const [searchQuery, setSearchQuery] = useState("");
  const [suggestions, setSuggestions] = useState<
    {
      [x: string]: string;
      uniqueID: string;
      slug: string;
      organisationName: string;
    }[]
  >([]);
  const [isLoading, setIsLoading] = useState(false);

  // Placeholder text based on the selected radio button
  const getPlaceholder = () => {
    return selected === "hs-radio-group-1"
      ? "Organization"
      : "Unique Identification Number";
  };

  // Handle radio button change
  const handleRadioChange = (id: string) => {
    setSelected(id);
    setSearchQuery(""); // Reset search input when changing selection
    setSuggestions([]); // Clear suggestions
  };

  // Handle form submission
  const handleSearch = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (searchQuery.trim() && suggestions.length > 0) {
      // Redirect to the first suggestion if available
      router.push(`/organizationbody/${suggestions[0].slug}`);
    }
  };

  // Fetch suggestions based on search query
  const fetchSuggestions = async () => {
    const trimmedQuery = searchQuery.trim().toLowerCase();
    if (!trimmedQuery) {
      setSuggestions([]);
      return;
    }

    setIsLoading(true);

    try {
      // Use the same query parameter name for both search types
      const paramName = "searchQuery";
      const response = await axios.get(
        `${BASE_URL}organisation/searchOrforHome?${paramName}=${trimmedQuery}`
      );

      // The backend now handles searching by either name or uniqueId,
      // so you don't need separate logic here.
      setSuggestions(response.data.data || []);
    } catch (error) {
      console.error("Error fetching search results:", error);
      setSuggestions([]);
    } finally {
      setIsLoading(false);
    }
  };

  // Use useEffect to debounce the search
  useEffect(() => {
    const timer = setTimeout(() => {
      if (searchQuery.trim()) {
        fetchSuggestions();
      } else {
        setSuggestions([]);
      }
    }, 300); // 300ms debounce

    return () => clearTimeout(timer);
  }, [searchQuery, selected]);

  return (
    <div className="w-full">
      <div className="mx-auto max-w-4xl px-9 pt-20 text-center">
        <h1>{data?.pageSubTitle} </h1>
        <div className="safe">
          <SafeHtmlRenderer htmlContent={data?.fullContent} />
        </div>

        <div className="flex justify-center flex-col m-auto md:w-[75%]">
          <h3 className="text-2xl mb-3 text-start">Certified Organization</h3>
          <div className="flex flex-row md:flex-row flex-col gap-x-6 mb-3">
            {[
              {
                id: "hs-radio-group-1",
                label: "Name of Organization",
              },
              {
                id: "hs-radio-group-2",
                label: "Unique Identification Number",
              },
            ].map((item) => (
              <div className="flex" key={item.id}>
                <input
                  type="radio"
                  name="hs-radio-group"
                  className="shrink-0 mt-0.5 border-gray-200 rounded-full text-blue-600 focus:ring-blue-500 checked:border-blue-500 disabled:opacity-50 disabled:pointer-events-none"
                  id={item.id}
                  checked={selected === item.id}
                  onChange={() => handleRadioChange(item.id)}
                />
                <label htmlFor={item.id} className="text-sm text-gray-500 ms-2">
                  {item.label}
                </label>
              </div>
            ))}
          </div>
          <form
            onSubmit={handleSearch}
            className="flex mb-8 flex-col items-center sm:flex-row justify-center relative"
          >
            <div className="relative flex w-full flex-1">
              <input
                type="text"
                className="w-full px-4 py-2 border text-sm bg-white/25 pr-10"
                placeholder={getPlaceholder()}
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
              />
              {searchQuery && (
                <button
                  type="button"
                  className="absolute right-12 top-1/2 transform -translate-y-1/2 text-gray-500 hover:text-gray-700"
                  onClick={() => {
                    setSearchQuery("");
                    setSuggestions([]);
                  }}
                >
                  ✕
                </button>
              )}
              <button
                type="submit"
                className="flex items-center justify-center rounded-r-md bg-gray-100 px-4 py-2 text-gray-600 hover:bg-btn focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
                disabled={isLoading}
              >
                {isLoading ? (
                  <div className="h-5 w-5 border-2 border-t-transparent border-blue-600 rounded-full animate-spin"></div>
                ) : (
                  <svg
                    className="h-5 w-5"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
                    />
                  </svg>
                )}
                <span className="sr-only">Search</span>
              </button>

              {/* Suggestions dropdown */}
              {/* {suggestions.length > 0 && (
                <div className="absolute top-full left-0 right-0 bg-white border border-gray-200 mt-1 rounded-md shadow-lg z-10 max-h-60 overflow-y-auto">
                  {suggestions.map((item, index) => (
                    <div
                      key={index}
                      className="px-4 py-2 hover:bg-gray-100 cursor-pointer text-left"
                      onClick={() => {
                        if (selected === "hs-radio-group-2") {
                          router.push(`/organizationbody/${item.slug}`);
                        } else {
                          router.push(`/organizationbody/${item.slug}`);
                        }
                      }}
                    >
                      {selected === "hs-radio-group-2"
                        ? item.uniqueID
                        : item.organisationName}
                    </div>
                  ))}
                </div>
              )} */}

              {suggestions.length > 0 && (
                <ul className="absolute gap-1 top-full left-0 right-0 z-10 bg-white border border-gray-200 shadow-md rounded-md max-h-48 overflow-auto mt-1">
                  {suggestions.map((item, index) => (
                    <li
                      key={item?.uniqueID || item.slug || index}
                      className="px-4 py-2 hover:bg-gray-100 cursor-pointer text-left"
                      onClick={() =>
                        router.push(`/organizationbody/${item.slug}`)
                      }
                    >
                      {selected === "hs-radio-group-1"
                        ? item.organisationName
                        : item.uniqueID}
                    </li>
                  ))}
                </ul>
              )}

              {/* No results message */}
              {searchQuery && !isLoading && suggestions.length === 0 && (
                <div className="absolute top-full left-0 right-0 bg-white border border-gray-200 mt-1 rounded-md shadow-lg z-10 p-4 text-gray-500">
                  No results found for "{searchQuery}"
                </div>
              )}
            </div>
          </form>
        </div>
      </div>
    </div>
  );
}
