// app/search-results/page.tsx
"use client";
import { useState, useEffect } from "react";
import { useSearchParams } from "next/navigation";
import axios from "axios";
import { BASE_URL } from "@/Constant";
import useAxios from "@/hooks/useAxios"; // Make sure this import is correct

import { ExternalLink } from "lucide-react";

interface Country {
  _id: string;
  billcountryid: string;
  sortname: string;
  billcountry: string;
  phonecode: string;
}

export default function SearchResultsPage() {
  const { getData } = useAxios();
  const searchParams = useSearchParams();
  const [results, setResults] = useState([]);
  const [loading, setLoading] = useState(true);
  const [allCountries, setAllCountries] = useState<Country[]>([]);
  const [countryMap, setCountryMap] = useState<Map<string, string>>(new Map());

  const [filters, setFilters] = useState({
    searchQuery: searchParams.get("searchQuery") || "",
    standard: searchParams.get("standard") || "",
    approvalStatus: searchParams.get("approvalStatus") || "",
    country: searchParams.get("country") || "",
    type: searchParams.get("type") || "name",
    modelType: searchParams.get("modelType") || "personal",
  });

  // Fetch countries first
  const fetchCountries = async () => {
    try {
      const response: any = await getData("dropdown/getAllCountry");
      if (response?.data) {
        const countries: Country[] = response.data;
        setAllCountries(countries);

        // Create a map of country ID to country name
        const map = new Map<string, string>();
        countries.forEach((country) => {
          map.set(country.billcountryid, country.billcountry);
        });
        setCountryMap(map);
      }
    } catch (error) {
      console.error("Error fetching countries:", error);
    }
  };

  // Fetch countries on component mount
  useEffect(() => {
    fetchCountries();
  }, []);

  const fetchResults = async () => {
    setLoading(true);
    try {
      let endpoint;
      let queryParams = `searchQuery=${filters.searchQuery}&type=${filters.type}`;

      if (
        filters.modelType === "personal" &&
        (filters.standard || filters.approvalStatus || filters.country)
      ) {
        endpoint = `${BASE_URL}personal/searchPersonalForHomeWithFilters`;

        if (filters.standard) {
          queryParams += `&standard=${encodeURIComponent(filters.standard)}`;
        }
        if (filters.approvalStatus) {
          queryParams += `&approvalStatus=${encodeURIComponent(
            filters.approvalStatus,
          )}`;
        }
        if (filters.country) {
          queryParams += `&country=${encodeURIComponent(filters.country)}`;
        }
      } else if (filters.modelType === "organization") {
        endpoint = `${BASE_URL}organisation/searchOrforHome`;
      } else {
        endpoint = `${BASE_URL}personal/searchPersonalForHome`;
      }

      const response = await axios.get(`${endpoint}?${queryParams}`);
      setResults(response.data.data || []);
    } catch (error) {
      console.error("Error fetching results:", error);
      setResults([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchResults();
  }, [searchParams]);

  // Helper function to parse standards
  const parseStandards = (standardsData: any) => {
    try {
      if (!standardsData || !Array.isArray(standardsData)) return [];

      const allStandards: string[] = [];

      standardsData.forEach((standardItem) => {
        if (typeof standardItem === "string") {
          try {
            const parsed = JSON.parse(standardItem);
            if (Array.isArray(parsed)) {
              parsed.forEach((item: any) => {
                if (item.standardNumber) {
                  allStandards.push(item.standardNumber);
                }
              });
            } else if (parsed.standardNumber) {
              allStandards.push(parsed.standardNumber);
            }
          } catch (e) {
            allStandards.push(standardItem);
          }
        } else if (typeof standardItem === "object" && standardItem !== null) {
          if (standardItem.standardNumber) {
            allStandards.push(standardItem.standardNumber);
          }
        }
      });

      return [...new Set(allStandards)];
    } catch (error) {
      console.error("Error parsing standards:", error);
      return [];
    }
  };

  // Helper function to parse glaApprovalStatus
  const parseApprovalStatus = (standardsData: any) => {
    try {
      if (!standardsData || !Array.isArray(standardsData)) return [];

      const allStatuses: string[] = [];

      standardsData.forEach((standardItem) => {
        if (typeof standardItem === "string") {
          try {
            const parsed = JSON.parse(standardItem);
            if (Array.isArray(parsed)) {
              parsed.forEach((item: any) => {
                if (item.glaApprovalStatus) {
                  allStatuses.push(item.glaApprovalStatus);
                }
              });
            } else if (parsed.glaApprovalStatus) {
              allStatuses.push(parsed.glaApprovalStatus);
            }
          } catch (e) {}
        } else if (typeof standardItem === "object" && standardItem !== null) {
          if (standardItem.glaApprovalStatus) {
            allStatuses.push(standardItem.glaApprovalStatus);
          }
        }
      });

      return [...new Set(allStatuses)];
    } catch (error) {
      console.error("Error parsing approval status:", error);
      return [];
    }
  };

  // ✅ UPDATED: Parse countries from KeyLocation and convert ID to name
  const parseCountries = (keyLocation: any) => {
    try {
      if (!keyLocation || !Array.isArray(keyLocation)) return [];

      // Extract country IDs from KeyLocation
      const countryIds = keyLocation
        .map((location) => location?.country)
        .filter((countryId) => countryId && typeof countryId === "string")
        .map((countryId) => countryId.trim());

      // Convert IDs to country names using the map
      const countryNames = countryIds.map((id) => {
        const name = countryMap.get(id);
        return name || id; // If name not found, show ID as fallback
      });

      // Remove duplicates
      return [...new Set(countryNames)];
    } catch (error) {
      console.error("Error parsing countries from KeyLocation:", error);
      return [];
    }
  };

  // Get status color based on approval status
  const getStatusColor = (status: string) => {
    switch (status?.toLowerCase()) {
      case "lead implementor":
        return "bg-purple-100 text-purple-800 border-purple-200";
      case "trainer":
        return "bg-blue-100 text-blue-800 border-blue-200";
      case "associate auditor":
        return "bg-green-100 text-green-800 border-green-200";
      case "consultant":
        return "bg-yellow-100 text-yellow-800 border-yellow-200";
      case "implementor":
        return "bg-indigo-100 text-indigo-800 border-indigo-200";
      default:
        return "bg-gray-100 text-gray-800 border-gray-200";
    }
  };

  return (
    <div className="bg-gray-50 min-h-screen">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-4">
            Certified Personal Data
          </h1>

          {/* Results Table */}
          <div className="bg-white shadow-lg rounded-xl overflow-hidden">
            {loading ? (
              <div className="flex justify-center items-center h-64">
                <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-purple-600"></div>
              </div>
            ) : results.length > 0 ? (
              <div className="overflow-x-auto">
                <table className="min-w-full divide-y divide-gray-200">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="px-4 sm:px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Name
                      </th>
                      <th className="px-4 sm:px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Standards
                      </th>
                      <th className="px-4 sm:px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Certification Type
                      </th>
                      <th className="px-4 sm:px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Countries
                      </th>
                      <th className="px-4 sm:px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Actions
                      </th>
                    </tr>
                  </thead>
                  <tbody className="bg-white divide-y divide-gray-200">
                    {results.map((item: any, index) => {
                      const standards = parseStandards(item.standards);
                      const approvalStatuses = parseApprovalStatus(
                        item.standards,
                      );
                      // ✅ Convert country IDs to names
                      const countries = parseCountries(item.KeyLocation);

                      return (
                        <tr
                          key={index}
                          className="hover:bg-gray-50 transition-colors"
                        >
                          {/* Name Column */}
                          <td className="px-4 sm:px-6 py-4 whitespace-nowrap">
                            <div className="text-sm font-medium text-gray-900">
                              {item.organisationName || item.personalName}
                            </div>
                            {item.uniqueID && (
                              <div className="text-xs text-gray-500 mt-1">
                                ID: {item.uniqueID}
                              </div>
                            )}
                          </td>

                          {/* Standards Column */}
                          <td className="px-4 sm:px-6 py-4">
                            <div className="">
                              {standards && standards.length > 0 ? (
                                <div className="max-h-[120px] overflow-y-auto pr-2 custom-scrollbar">
                                  <div className="flex flex-col gap-1">
                                    {standards.map(
                                      (standard: string, idx: number) => (
                                        <span
                                          key={idx}
                                          className="px-2 py-1 text-xs bg-purple-50 text-purple-700 rounded border border-purple-100 font-medium mb-1 whitespace-nowrap"
                                        >
                                          {standard}
                                        </span>
                                      ),
                                    )}
                                  </div>
                                </div>
                              ) : (
                                <span className="text-sm text-gray-400 italic">
                                  No standards
                                </span>
                              )}
                            </div>
                          </td>

                          {/* Approval Status Column */}
                          <td className="px-4 sm:px-6 py-4">
                            <div className="max-w-[200px]">
                              {approvalStatuses &&
                              approvalStatuses.length > 0 ? (
                                <div className="max-h-[120px] overflow-y-auto pr-2 custom-scrollbar">
                                  <div className="flex flex-col gap-1">
                                    {approvalStatuses.map(
                                      (status: string, idx: number) => (
                                        <span
                                          key={idx}
                                          className={`px-2 py-1 text-xs rounded border mb-1 whitespace-nowrap ${getStatusColor(
                                            status,
                                          )}`}
                                        >
                                          {status}
                                        </span>
                                      ),
                                    )}
                                  </div>
                                </div>
                              ) : (
                                <span className="text-sm text-gray-400 italic">
                                  No status
                                </span>
                              )}
                            </div>
                          </td>

                          {/* ✅ Countries Column - Now showing names instead of IDs */}
                          <td className="px-4 sm:px-6 py-4">
                            <div className="max-w-[200px]">
                              {countries && countries.length > 0 ? (
                                <div className="max-h-[120px] overflow-y-auto pr-2 custom-scrollbar">
                                  <div className="flex flex-col gap-1">
                                    {countries
                                      .slice(0, 10)
                                      .map((country: string, idx: number) => (
                                        <span
                                          key={idx}
                                          className="px-2 py-1 text-xs bg-blue-50 text-blue-700 rounded border border-blue-100 mb-1 whitespace-nowrap"
                                        >
                                          {country}{" "}
                                          {/* ✅ Now showing country name like "Afghanistan" */}
                                        </span>
                                      ))}
                                    {countries.length > 10 && (
                                      <span className="px-2 py-1 text-xs bg-gray-100 text-gray-600 rounded border border-gray-200">
                                        +{countries.length - 10} more countries
                                      </span>
                                    )}
                                  </div>
                                </div>
                              ) : (
                                <span className="text-sm text-gray-400 italic">
                                  No countries
                                </span>
                              )}
                            </div>
                          </td>

                          {/* Actions Column */}
                          <td className="px-4 sm:px-6 py-4 whitespace-nowrap text-sm font-medium">
                            <a
                              href={`/personalbody/${encodeURIComponent(
                                (item.slug || item.slug).replace(/\//g, "---"),
                              )}`}
                              className="inline-flex items-center bg-btn-ob gap-1 px-3 py-1.5 bg-blue-50 text-blue-700 hover:bg-blue-100 border border-blue-200 rounded-lg transition-colors text-sm font-medium"
                            >
                              View Details
                              <ExternalLink className="w-3 h-3" />
                            </a>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            ) : (
              <div className="text-center py-12">
                <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-gray-100 flex items-center justify-center">
                  <svg
                    className="w-8 h-8 text-gray-400"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
                    />
                  </svg>
                </div>
                <h3 className="text-lg font-semibold text-gray-900 mb-2">
                  No results found
                </h3>
                <p className="text-gray-500">
                  Try adjusting your search or filters
                </p>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Custom CSS for scrollbar */}
      <style jsx global>{`
        .custom-scrollbar {
          scrollbar-width: thin;
          scrollbar-color: #c7d2fe #f1f1f1;
        }
        .custom-scrollbar::-webkit-scrollbar {
          width: 6px;
        }
        .custom-scrollbar::-webkit-scrollbar-track {
          background: #f1f1f1;
          border-radius: 10px;
        }
        .custom-scrollbar::-webkit-scrollbar-thumb {
          background: #c7d2fe;
          border-radius: 10px;
        }
        .custom-scrollbar::-webkit-scrollbar-thumb:hover {
          background: #a5b4fc;
        }
        @media (max-width: 768px) {
          .min-w-full {
            min-width: 800px;
          }
        }
      `}</style>
    </div>
  );
}
