"use client";

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 Hero({ data }: any) {
  const router = useRouter();
  const [selected, setSelected] = useState("hs-radio-group-1");
  const [searchQuery, setSearchQuery] = useState("");
  const [suggestions, setSuggestions] = useState<
    {
      uniqueID?: string;
      uniqueId?: string;
      organisationName: string;
      slug: string;
      type: "organisation" | "personal";
      fullName?: string;
    }[]
  >([]);
  const [isLoading, setIsLoading] = useState(false);

  const getPlaceholder = () => {
    return selected === "hs-radio-group-1"
      ? "Search Verified by Organization / Name of Personal"
      : "Search Verified by Unique Identification Number";
  };

  const handleRadioChange = (id: string) => {
    setSelected(id);
    setSearchQuery("");
    setSuggestions([]);
  };

  const handleSearch = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (searchQuery.trim() && suggestions.length > 0) {
      const firstSuggestion = suggestions[0];
      redirectToSuggestion(firstSuggestion);
    }
  };

  const fetchSuggestions = async () => {
    const trimmedQuery = searchQuery.trim().toLowerCase();
    if (!trimmedQuery) {
      setSuggestions([]);
      return;
    }

    setIsLoading(true);

    try {
      let searchType = "";
      if (selected === "hs-radio-group-1") {
        searchType = "name";
      } else {
        searchType = "uniqueID";
      }

      const response = await axios.get(
        `${BASE_URL}organisation/searchOrforHome?searchQuery=${trimmedQuery}&type=${searchType}`,
      );
      const formattedSuggestions = (response.data.data || []).map(
        (item: any) => ({
          ...item,
          uniqueID: item.type === "personal" ? item.uniqueID : item.uniqueId,
          slug: item.type === "personal" ? item.uniqueID : item.slug,
        }),
      );

      setSuggestions(formattedSuggestions);
    } catch (error) {
      console.error("Error fetching search results:", error);
      setSuggestions([]);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    const timer = setTimeout(() => {
      if (searchQuery.trim()) {
        fetchSuggestions();
      } else {
        setSuggestions([]);
      }
    }, 300);

    return () => clearTimeout(timer);
  }, [searchQuery, selected]);

  // 🔥 FIXED: Properly format the slug for URL
  const formatUniqueIDForURL = (slug: string) => {
    // Option 1: Convert both slashes AND hyphens to underscores
    // This will make "UI-XNU/89/89" -> "UI_XNU_89_89"
    return encodeURIComponent(slug.replace(/\//g, "_").replace(/-/g, "_"));

    // Option 2: Convert ONLY slashes to underscores, keep hyphens as is
    // This will make "UI-XNU/89/89" -> "UI-XNU_89_89"
    // return encodeURIComponent(slug.replace(/\//g, '_'));
  };

  const redirectToSuggestion = (suggestion: any) => {
    if (suggestion.type === "organisation") {
      router.push(`/organizationbody/${formatUniqueIDForURL(suggestion.slug)}`);
    } else {
      router.push(
        `/personalbody/${formatUniqueIDForURL(suggestion.slug || suggestion.slug)}`,
      );
    }
  };

  const handleSuggestionClick = (suggestion: any) => {
    redirectToSuggestion(suggestion);
  };

  // Format display text for suggestions based on selected radio button
  const getSuggestionDisplayText = (item: any) => {
    if (selected === "hs-radio-group-1") {
      // Name search - ALWAYS show organisationName for both types
      return `${item.organisationName}`;
    } else {
      // Unique ID search - show unique ID
      return `${item.uniqueID || item.uniqueId || "N/A"}`;
    }
  };

  const getSuggestionSubText = (item: any) => {
    return item.type === "organisation" ? "Organization" : "Certified Personal";
  };

  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 / Name of Personal
          </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 / Name of Personal",
              },
              {
                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-3 flex flex-row gap-2 hover:bg-gray-100 cursor-pointer text-left border-b last:border-b-0"
                      onClick={() => handleSuggestionClick(item)}
                    >
                      <div className="font-medium text-gray-900">
                        {getSuggestionDisplayText(item)}
                      </div>
                      <div className="text-xs text-gray-500 mt-1">
                        {getSuggestionSubText(item)}
                      </div>
                    </div>
                  ))}
                </div>
              )}

              {/* 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>
  );
}
