"use client";
import React, { useState, useEffect, useRef } from "react";
import SafeHtmlRenderer from "../SafeHtmlRenderer";
import { useRouter } from "next/navigation";
import axios from "axios";
import { BASE_URL } from "@/Constant";
import GlaApply from "../Gla/GlaApply";

function HeroCertificationBody({ main, table }: any) {
  const [selected, setSelected] = useState("hs-radio-group-1");
  const [searchQuery, setSearchQuery] = useState("");
  const [showSuggestions, setShowSuggestions] = useState(false);
  const searchRef = useRef<HTMLDivElement>(null);

  interface Suggestion {
    uniqueId: string;
    slug: string;
    organisationName: string;
    uniqueID: string;
  }

  const [suggestions, setSuggestions] = useState<Suggestion[]>([]);
  const router = useRouter();

  const getPlaceholder = () =>
    selected === "hs-radio-group-1"
      ? "Name of Organization"
      : "Unique Identification Number";

  const handleRadioChange = (id: string) => {
    setSelected(id);
    setSearchQuery("");
    setSuggestions([]);
    setShowSuggestions(false);
  };

  const handleSearch = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
  };

  const formatUniqueIDForURL = (uniqueID: string) => {
    return encodeURIComponent(uniqueID.replace(/\//g, "---"));
  };

  const fetchCertificationBodyList = async () => {
    const trimmedQuery = searchQuery.trim();

    if (!trimmedQuery) {
      setSuggestions([]);
      setShowSuggestions(false);
      return;
    }

    try {
      let type = selected === "hs-radio-group-1" ? "name" : "uniqueID";
      const res = await axios.get(
        `${BASE_URL}cb/searchCb?searchQuery=${trimmedQuery}&type=${type}`,
      );

      setSuggestions(res.data.data || []);
      setShowSuggestions(true);
    } catch (error) {
      setSuggestions([]);
      setShowSuggestions(false);
    }
  };

  // Click outside to close suggestions
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        searchRef.current &&
        !searchRef.current.contains(event.target as Node)
      ) {
        setShowSuggestions(false);
      }
    };

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

  useEffect(() => {
    // Debounce the API call
    const timer = setTimeout(() => {
      fetchCertificationBodyList();
    }, 300); // 300ms delay

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

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchQuery(e.target.value);
    // Hide suggestions immediately when user starts deleting
    if (e.target.value === "") {
      setShowSuggestions(false);
      setSuggestions([]);
    }
  };

  const handleSuggestionClick = (item: Suggestion) => {
    router.push(`/certificationbody/${formatUniqueIDForURL(item.slug)}`);
    setShowSuggestions(false);
    setSearchQuery(
      selected === "hs-radio-group-1" ? item.organisationName : item.uniqueID,
    );
  };

  return (
    <div className="container m-auto overflow-hidden pt-16">
      {/* Title Section */}
      <div className="mx-auto max-w-4xl px-4 text-center">
        <h1>{main?.cb?.pageTitle}</h1>
        <div className="safe">
          <SafeHtmlRenderer htmlContent={main?.cb?.pageSubTitle} />
        </div>
      </div>

      {/* Search Section */}
      <div className="w-full mb-5">
        <div className="mx-auto max-w-4xl px-9 pt-3 text-center">
          <div className="flex justify-center flex-col m-auto md:w-[75%]">
            {/* Radio Buttons */}
            <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"
                    id={item.id}
                    checked={selected === item.id}
                    onChange={() => handleRadioChange(item.id)}
                    className="shrink-0 mt-0.5 border-gray-200 rounded-full text-blue-600 focus:ring-blue-500"
                  />
                  <label
                    htmlFor={item.id}
                    className="text-sm text-gray-500 ms-2"
                  >
                    {item.label}
                  </label>
                </div>
              ))}
            </div>

            {/* Search Form */}
            <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" ref={searchRef}>
                <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400">
                  🔍
                </span>

                <input
                  type="text"
                  className="w-full pl-10 pr-10 py-2 border rounded-md text-sm bg-white placeholder-gray-400 focus:outline-none focus:ring-1 focus:ring-blue-400"
                  placeholder={getPlaceholder()}
                  value={searchQuery}
                  onChange={handleInputChange}
                  onFocus={() => {
                    if (suggestions.length > 0) {
                      setShowSuggestions(true);
                    }
                  }}
                />

                {searchQuery && (
                  <button
                    type="button"
                    onClick={() => {
                      setSearchQuery("");
                      setSuggestions([]);
                      setShowSuggestions(false);
                    }}
                    className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                  >
                    ✖
                  </button>
                )}

                {/* Suggestions List */}
                {showSuggestions && suggestions.length > 0 && (
                  <ul className="absolute top-full gap-1 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) => (
                      <li
                        key={item.uniqueId}
                        className="px-4 py-2 hover:bg-gray-100 cursor-pointer border-b border-gray-100 last:border-b-0"
                        onClick={() => handleSuggestionClick(item)}
                      >
                        {selected === "hs-radio-group-1"
                          ? item.organisationName
                          : item.uniqueID}
                      </li>
                    ))}
                  </ul>
                )}

                {/* No Results */}
                {showSuggestions && searchQuery && suggestions.length === 0 && (
                  <div className="absolute top-full left-0 right-0 bg-white border border-gray-200 shadow-md rounded-md px-4 py-2 text-gray-500 text-sm mt-1 z-10">
                    No results found
                  </div>
                )}
              </div>
            </form>
          </div>
        </div>
      </div>

      {/* Full Content */}
      <div className="container mx-auto px-4 pt-16">
        <div className="flex flex-col md:flex-row items-start justify-between">
          <div className="w-full mx-auto px-4 space-y-4">
            <div className="safe">
              <SafeHtmlRenderer htmlContent={main?.cb?.fullContent} />
            </div>
          </div>
        </div>
      </div>

      {/* Apply Section */}
      <div className="flex justify-center">
        <GlaApply />
      </div>
    </div>
  );
}

export default HeroCertificationBody;
