"use client";

import { useState, useMemo, useEffect, useRef } from "react";
import Link from "next/link";
import {
  SearchIcon,
  FilterIcon,
  XIcon,
  ArrowRightIcon,
  FactoryIcon,
  GlobeIcon,
  WheatIcon,
  MapPinIcon,
  ChevronDownIcon,
  CheckIcon,
} from "lucide-react";
import type { Mill } from "../_data/mills";
import Heading from "@/app/components/ui/Heading";

interface MillsGridProps {
  mills: Mill[];
}

const PAGE_SIZE = 30;

export default function MillsGrid({ mills }: MillsGridProps) {
  const [searchQuery, setSearchQuery] = useState("");
  const [selectedProvince, setSelectedProvince] = useState<string | null>(null);
  const [selectedCity, setSelectedCity] = useState<string | null>(null);
  const [selectedRiceProduct, setSelectedRiceProduct] = useState<string | null>(
    null,
  );
  const [selectedCertification, setSelectedCertification] = useState<
    string | null
  >(null);
  const [selectedMembership, setSelectedMembership] = useState<string | null>(
    null,
  );

  const [isFilterOpen, setIsFilterOpen] = useState(false);
  const [activeDropdown, setActiveDropdown] = useState<string | null>(null);
  const [citySearch, setCitySearch] = useState("");
  const [visibleCount, setVisibleCount] = useState(PAGE_SIZE);

  // Extract unique filter options
  const provinces = useMemo(() => {
    const set = new Set<string>();
    for (const m of mills) {
      if (m.province) set.add(m.province);
    }
    return Array.from(set).sort();
  }, [mills]);

  const cities = useMemo(() => {
    const set = new Set<string>();
    for (const m of mills) {
      if (selectedProvince) {
        if (m.province === selectedProvince && m.city) set.add(m.city);
      } else {
        if (m.city) set.add(m.city);
      }
    }
    return Array.from(set).sort();
  }, [mills, selectedProvince]);

  const filteredCities = useMemo(() => {
    if (!citySearch.trim()) return cities;
    const q = citySearch.toLowerCase().trim();
    return cities.filter((c) => c.toLowerCase().includes(q));
  }, [cities, citySearch]);

  const riceProducts = useMemo(() => {
    const counts = new Map<string, number>();
    for (const m of mills) {
      for (const p of m.riceProducts) {
        counts.set(p, (counts.get(p) || 0) + 1);
      }
    }
    return Array.from(counts.entries())
      .sort((a, b) => b[1] - a[1])
      .map(([name]) => name);
  }, [mills]);

  const certifications = useMemo(() => {
    const counts = new Map<string, number>();
    for (const m of mills) {
      for (const c of m.certifications) {
        counts.set(c, (counts.get(c) || 0) + 1);
      }
    }
    return Array.from(counts.entries())
      .sort((a, b) => b[1] - a[1])
      .map(([name]) => name);
  }, [mills]);

  const memberships = useMemo(() => {
    const set = new Set<string>();
    for (const m of mills) {
      for (const mem of m.tradeMemberships) {
        set.add(mem);
      }
    }
    return Array.from(set).sort();
  }, [mills]);

  // Filter mills
  const filteredMills = useMemo(() => {
    const q = searchQuery.toLowerCase().trim();
    return mills.filter((mill) => {
      // Text search across name, city, district, province, products, certifications, and exports
      const matchesQuery =
        !q ||
        mill.name.toLowerCase().includes(q) ||
        (mill.city && mill.city.toLowerCase().includes(q)) ||
        (mill.district && mill.district.toLowerCase().includes(q)) ||
        (mill.province && mill.province.toLowerCase().includes(q)) ||
        mill.riceProducts.some((p) => p.toLowerCase().includes(q)) ||
        mill.certifications.some((c) => c.toLowerCase().includes(q)) ||
        mill.exportDestinations.some((d) => d.toLowerCase().includes(q));

      if (!matchesQuery) return false;

      if (selectedProvince && mill.province !== selectedProvince) return false;
      if (selectedCity && mill.city !== selectedCity) return false;
      if (
        selectedRiceProduct &&
        !mill.riceProducts.includes(selectedRiceProduct)
      ) {
        return false;
      }
      if (
        selectedCertification &&
        !mill.certifications.includes(selectedCertification)
      ) {
        return false;
      }
      if (
        selectedMembership &&
        !mill.tradeMemberships.includes(selectedMembership)
      ) {
        return false;
      }

      return true;
    });
  }, [
    mills,
    searchQuery,
    selectedProvince,
    selectedCity,
    selectedRiceProduct,
    selectedCertification,
    selectedMembership,
  ]);

  // Reset pagination when filter changes
  const [prevFilterKey, setPrevFilterKey] = useState("");
  const filterKey = `${searchQuery}|${selectedProvince}|${selectedCity}|${selectedRiceProduct}|${selectedCertification}|${selectedMembership}`;

  if (filterKey !== prevFilterKey) {
    setPrevFilterKey(filterKey);
    setVisibleCount(PAGE_SIZE);
  }

  // Count active filters
  const activeFilterCount =
    (selectedProvince ? 1 : 0) +
    (selectedCity ? 1 : 0) +
    (selectedRiceProduct ? 1 : 0) +
    (selectedCertification ? 1 : 0) +
    (selectedMembership ? 1 : 0);

  const clearAllFilters = () => {
    setSelectedProvince(null);
    setSelectedCity(null);
    setSelectedRiceProduct(null);
    setSelectedCertification(null);
    setSelectedMembership(null);
    setActiveDropdown(null);
    setCitySearch("");
    setSearchQuery("");
  };

  const hasAnyFilter = activeFilterCount > 0 || Boolean(searchQuery);

  const displayedMills = filteredMills.slice(0, visibleCount);
  const hasMore = visibleCount < filteredMills.length;

  const filterGridRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!activeDropdown) return;
    const handleClickOutside = (event: MouseEvent) => {
      if (
        filterGridRef.current &&
        !filterGridRef.current.contains(event.target as Node)
      ) {
        setActiveDropdown(null);
        setCitySearch("");
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [activeDropdown]);

  return (
    <div>
      {/* Search Bar & Single Filter Button */}
      <div className="relative z-30 mb-8">
        <div className="flex flex-col sm:flex-row gap-3 items-stretch sm:items-center">
          {/* Search Input */}
          <div className="relative flex-1">
            <SearchIcon
              size={20}
              className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400"
            />
            <input
              type="text"
              placeholder="Search mills by name, city, province, variety, certification, or market..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full pl-12 pr-10 py-3.5 border border-gray-200 rounded-xl text-gray-800 placeholder:text-gray-400 focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary transition-colors duration-300 bg-white"
            />
            {searchQuery && (
              <button
                onClick={() => setSearchQuery("")}
                className="absolute right-3.5 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 p-1 cursor-pointer"
                title="Clear search text"
              >
                <XIcon size={16} />
              </button>
            )}
          </div>

          {/* Single Filter Button Right After Search Bar */}
          <button
            onClick={() => {
              setIsFilterOpen(!isFilterOpen);
              setActiveDropdown(null);
            }}
            className={`flex items-center justify-center gap-2 px-6 py-3.5 rounded-xl border transition-all duration-300 font-semibold text-sm cursor-pointer shrink-0 shadow-xs ${
              isFilterOpen || activeFilterCount > 0
                ? "bg-primary text-white border-primary shadow-sm"
                : "border-gray-200 text-gray-700 bg-white hover:border-primary hover:text-primary"
            }`}
          >
            <FilterIcon size={18} />
            <span>Filter</span>
            {activeFilterCount > 0 && (
              <span className="bg-white text-primary text-xs px-2 py-0.5 rounded-full font-bold">
                {activeFilterCount}
              </span>
            )}
          </button>

          {hasAnyFilter && (
            <button
              onClick={clearAllFilters}
              className="flex items-center justify-center gap-1.5 px-4 py-3.5 rounded-xl border border-gray-200 text-gray-500 hover:text-gray-800 hover:border-gray-300 bg-white text-sm font-medium transition-colors cursor-pointer shrink-0"
            >
              <XIcon size={16} />
              <span>Reset</span>
            </button>
          )}
        </div>

        {/* Animated Grid of Select Elements Appearing Just Below Search Bar */}
        <div
          ref={filterGridRef}
          className={`transition-all duration-400 ease-in-out relative z-30 ${
            isFilterOpen
              ? "opacity-100 mt-4 pointer-events-auto overflow-visible"
              : "opacity-0 mt-0 pointer-events-none overflow-hidden"
          }`}
          style={{
            display: "grid",
            gridTemplateRows: isFilterOpen ? "1fr" : "0fr",
            transition:
              "grid-template-rows 0.4s cubic-bezier(0.16, 1, 0.3, 1), opacity 0.35s ease, margin-top 0.35s ease",
          }}
        >
          <div className={isFilterOpen ? "overflow-visible" : "overflow-hidden"}>
            <div
              className={`p-5 bg-[#EFF8E1]/70 border border-[#467302]/25 rounded-2xl shadow-xs transition-all duration-400 ease-out relative z-30 ${
                isFilterOpen
                  ? "translate-y-0 overflow-visible"
                  : "-translate-y-2 overflow-hidden"
              }`}
            >
              <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-3.5 relative z-30">
                {/* 1. Province Filter */}
                <div className="flex flex-col gap-1.5 relative">
                  <label className="text-xs font-bold text-gray-700">
                    Province
                  </label>
                  <div className="relative">
                    <button
                      type="button"
                      onClick={() =>
                        setActiveDropdown(
                          activeDropdown === "province" ? null : "province",
                        )
                      }
                      className={`w-full flex items-center justify-between pl-4 pr-3.5 py-3 rounded-xl text-sm font-medium transition-all duration-200 text-left cursor-pointer focus:outline-none focus:ring-2 focus:ring-primary/20 ${
                        selectedProvince
                          ? "bg-[#EFF8E1] border-2 border-primary text-primary font-bold shadow-xs"
                          : "bg-white border border-gray-200 text-gray-800 hover:border-primary/60 hover:bg-gray-50/50 shadow-2xs"
                      }`}
                    >
                      <span className="truncate">
                        {selectedProvince || "All Provinces"}
                      </span>
                      <ChevronDownIcon
                        size={16}
                        className={`shrink-0 ml-2 transition-transform duration-300 ${
                          activeDropdown === "province"
                            ? "rotate-180 text-primary"
                            : selectedProvince
                              ? "text-primary"
                              : "text-gray-400"
                        }`}
                      />
                    </button>

                    {activeDropdown === "province" && (
                      <div className="absolute top-full left-0 mt-2 w-full min-w-[260px] sm:min-w-[280px] md:min-w-[320px] max-w-sm z-50 bg-white border border-[#467302]/30 rounded-2xl shadow-2xl p-1.5 max-h-72 overflow-y-auto">
                        <button
                          type="button"
                          onClick={() => {
                            setSelectedProvince(null);
                            setSelectedCity(null);
                            setActiveDropdown(null);
                          }}
                          className={`w-full px-3.5 py-2.5 rounded-xl text-left text-sm flex items-center justify-between cursor-pointer transition-colors ${
                            selectedProvince === null
                              ? "bg-[#EFF8E1] text-primary font-bold"
                              : "text-gray-700 hover:bg-[#EFF8E1]/60 hover:text-primary"
                          }`}
                        >
                          <span>All Provinces</span>
                          {selectedProvince === null && (
                            <CheckIcon
                              size={15}
                              className="text-primary shrink-0 ml-2"
                            />
                          )}
                        </button>
                        {provinces.map((prov) => {
                          const isSelected = selectedProvince === prov;
                          return (
                            <button
                              key={`prov-${prov}`}
                              type="button"
                              onClick={() => {
                                setSelectedProvince(prov);
                                setSelectedCity(null);
                                setActiveDropdown(null);
                              }}
                              className={`w-full px-3.5 py-2.5 rounded-xl text-left text-sm flex items-center justify-between cursor-pointer transition-colors ${
                                isSelected
                                  ? "bg-[#EFF8E1] text-primary font-bold"
                                  : "text-gray-700 hover:bg-[#EFF8E1]/60 hover:text-primary"
                              }`}
                            >
                              <span className="truncate">{prov}</span>
                              {isSelected && (
                                <CheckIcon
                                  size={15}
                                  className="text-primary shrink-0 ml-2"
                                />
                              )}
                            </button>
                          );
                        })}
                      </div>
                    )}
                  </div>
                </div>

                {/* 2. City Filter */}
                <div className="flex flex-col gap-1.5 relative">
                  <label className="text-xs font-bold text-gray-700">
                    City
                  </label>
                  <div className="relative">
                    <button
                      type="button"
                      onClick={() =>
                        setActiveDropdown(
                          activeDropdown === "city" ? null : "city",
                        )
                      }
                      className={`w-full flex items-center justify-between pl-4 pr-3.5 py-3 rounded-xl text-sm font-medium transition-all duration-200 text-left cursor-pointer focus:outline-none focus:ring-2 focus:ring-primary/20 ${
                        selectedCity
                          ? "bg-[#EFF8E1] border-2 border-primary text-primary font-bold shadow-xs"
                          : "bg-white border border-gray-200 text-gray-800 hover:border-primary/60 hover:bg-gray-50/50 shadow-2xs"
                      }`}
                    >
                      <span className="truncate">
                        {selectedCity || "All Cities"}
                      </span>
                      <ChevronDownIcon
                        size={16}
                        className={`shrink-0 ml-2 transition-transform duration-300 ${
                          activeDropdown === "city"
                            ? "rotate-180 text-primary"
                            : selectedCity
                              ? "text-primary"
                              : "text-gray-400"
                        }`}
                      />
                    </button>

                    {activeDropdown === "city" && (
                      <div className="absolute top-full left-0 mt-2 w-full min-w-[260px] sm:min-w-[280px] md:min-w-[320px] max-w-sm z-50 bg-white border border-[#467302]/30 rounded-2xl shadow-2xl overflow-hidden p-1.5 max-h-72 overflow-y-auto">
                        <div className="p-2 border-b border-gray-100 sticky top-0 bg-white z-10">
                          <input
                            type="text"
                            placeholder="Search city..."
                            value={citySearch}
                            onChange={(e) => setCitySearch(e.target.value)}
                            className="w-full px-3 py-2 text-sm border border-gray-200 rounded-xl focus:outline-none focus:border-primary"
                          />
                        </div>
                        <button
                          type="button"
                          onClick={() => {
                            setSelectedCity(null);
                            setActiveDropdown(null);
                            setCitySearch("");
                          }}
                          className={`w-full px-3.5 py-2.5 rounded-xl text-left text-sm flex items-center justify-between cursor-pointer transition-colors ${
                            selectedCity === null
                              ? "bg-[#EFF8E1] text-primary font-bold"
                              : "text-gray-700 hover:bg-[#EFF8E1]/60 hover:text-primary"
                          }`}
                        >
                          <span>All Cities</span>
                          {selectedCity === null && (
                            <CheckIcon
                              size={15}
                              className="text-primary shrink-0 ml-2"
                            />
                          )}
                        </button>
                        {filteredCities.map((city) => {
                          const isSelected = selectedCity === city;
                          return (
                            <button
                              key={`city-${city}`}
                              type="button"
                              onClick={() => {
                                setSelectedCity(city);
                                setActiveDropdown(null);
                                setCitySearch("");
                              }}
                              className={`w-full px-3.5 py-2.5 rounded-xl text-left text-sm flex items-center justify-between cursor-pointer transition-colors ${
                                isSelected
                                  ? "bg-[#EFF8E1] text-primary font-bold"
                                  : "text-gray-700 hover:bg-[#EFF8E1]/60 hover:text-primary"
                              }`}
                            >
                              <span className="truncate">{city}</span>
                              {isSelected && (
                                <CheckIcon
                                  size={15}
                                  className="text-primary shrink-0 ml-2"
                                />
                              )}
                            </button>
                          );
                        })}
                        {filteredCities.length === 0 && (
                          <p className="p-4 text-sm text-gray-400 text-center">
                            No matching city
                          </p>
                        )}
                      </div>
                    )}
                  </div>
                </div>

                {/* 3. Rice Varieties & Products Filter */}
                <div className="flex flex-col gap-1.5 relative">
                  <label className="text-xs font-bold text-gray-700">
                    Rice Variety / Product
                  </label>
                  <div className="relative">
                    <button
                      type="button"
                      onClick={() =>
                        setActiveDropdown(
                          activeDropdown === "rice" ? null : "rice",
                        )
                      }
                      className={`w-full flex items-center justify-between pl-4 pr-3.5 py-3 rounded-xl text-sm font-medium transition-all duration-200 text-left cursor-pointer focus:outline-none focus:ring-2 focus:ring-primary/20 ${
                        selectedRiceProduct
                          ? "bg-[#EFF8E1] border-2 border-primary text-primary font-bold shadow-xs"
                          : "bg-white border border-gray-200 text-gray-800 hover:border-primary/60 hover:bg-gray-50/50 shadow-2xs"
                      }`}
                    >
                      <span className="truncate">
                        {selectedRiceProduct || "All Rice Products"}
                      </span>
                      <ChevronDownIcon
                        size={16}
                        className={`shrink-0 ml-2 transition-transform duration-300 ${
                          activeDropdown === "rice"
                            ? "rotate-180 text-primary"
                            : selectedRiceProduct
                              ? "text-primary"
                              : "text-gray-400"
                        }`}
                      />
                    </button>

                    {activeDropdown === "rice" && (
                      <div className="absolute top-full left-0 mt-2 w-full min-w-[260px] sm:min-w-[280px] md:min-w-[320px] max-w-sm z-50 bg-white border border-[#467302]/30 rounded-2xl shadow-2xl p-1.5 max-h-72 overflow-y-auto">
                        <button
                          type="button"
                          onClick={() => {
                            setSelectedRiceProduct(null);
                            setActiveDropdown(null);
                          }}
                          className={`w-full px-3.5 py-2.5 rounded-xl text-left text-sm flex items-center justify-between cursor-pointer transition-colors ${
                            selectedRiceProduct === null
                              ? "bg-[#EFF8E1] text-primary font-bold"
                              : "text-gray-700 hover:bg-[#EFF8E1]/60 hover:text-primary"
                          }`}
                        >
                          <span>All Rice Products</span>
                          {selectedRiceProduct === null && (
                            <CheckIcon
                              size={15}
                              className="text-primary shrink-0 ml-2"
                            />
                          )}
                        </button>
                        {riceProducts.map((prod) => {
                          const isSelected = selectedRiceProduct === prod;
                          return (
                            <button
                              key={`rice-${prod}`}
                              type="button"
                              onClick={() => {
                                setSelectedRiceProduct(prod);
                                setActiveDropdown(null);
                              }}
                              className={`w-full px-3.5 py-2.5 rounded-xl text-left text-sm flex items-center justify-between cursor-pointer transition-colors ${
                                isSelected
                                  ? "bg-[#EFF8E1] text-primary font-bold"
                                  : "text-gray-700 hover:bg-[#EFF8E1]/60 hover:text-primary"
                              }`}
                            >
                              <span className="truncate">{prod}</span>
                              {isSelected && (
                                <CheckIcon
                                  size={15}
                                  className="text-primary shrink-0 ml-2"
                                />
                              )}
                            </button>
                          );
                        })}
                      </div>
                    )}
                  </div>
                </div>

                {/* 4. Certifications Filter */}
                <div className="flex flex-col gap-1.5 relative">
                  <label className="text-xs font-bold text-gray-700">
                    Quality Certification
                  </label>
                  <div className="relative">
                    <button
                      type="button"
                      onClick={() =>
                        setActiveDropdown(
                          activeDropdown === "cert" ? null : "cert",
                        )
                      }
                      className={`w-full flex items-center justify-between pl-4 pr-3.5 py-3 rounded-xl text-sm font-medium transition-all duration-200 text-left cursor-pointer focus:outline-none focus:ring-2 focus:ring-primary/20 ${
                        selectedCertification
                          ? "bg-[#EFF8E1] border-2 border-primary text-primary font-bold shadow-xs"
                          : "bg-white border border-gray-200 text-gray-800 hover:border-primary/60 hover:bg-gray-50/50 shadow-2xs"
                      }`}
                    >
                      <span className="truncate">
                        {selectedCertification || "All Certifications"}
                      </span>
                      <ChevronDownIcon
                        size={16}
                        className={`shrink-0 ml-2 transition-transform duration-300 ${
                          activeDropdown === "cert"
                            ? "rotate-180 text-primary"
                            : selectedCertification
                              ? "text-primary"
                              : "text-gray-400"
                        }`}
                      />
                    </button>

                    {activeDropdown === "cert" && (
                      <div className="absolute top-full right-0 lg:left-auto lg:right-0 mt-2 w-full min-w-[260px] sm:min-w-[280px] md:min-w-[340px] max-w-md z-50 bg-white border border-[#467302]/30 rounded-2xl shadow-2xl p-1.5 max-h-72 overflow-y-auto">
                        <button
                          type="button"
                          onClick={() => {
                            setSelectedCertification(null);
                            setActiveDropdown(null);
                          }}
                          className={`w-full px-3.5 py-2.5 rounded-xl text-left text-sm flex items-center justify-between cursor-pointer transition-colors ${
                            selectedCertification === null
                              ? "bg-[#EFF8E1] text-primary font-bold"
                              : "text-gray-700 hover:bg-[#EFF8E1]/60 hover:text-primary"
                          }`}
                        >
                          <span>All Certifications</span>
                          {selectedCertification === null && (
                            <CheckIcon
                              size={15}
                              className="text-primary shrink-0 ml-2"
                            />
                          )}
                        </button>
                        {certifications.map((cert) => {
                          const isSelected = selectedCertification === cert;
                          return (
                            <button
                              key={`cert-${cert}`}
                              type="button"
                              onClick={() => {
                                setSelectedCertification(cert);
                                setActiveDropdown(null);
                              }}
                              className={`w-full px-3.5 py-2.5 rounded-xl text-left text-sm flex items-center justify-between cursor-pointer transition-colors ${
                                isSelected
                                  ? "bg-[#EFF8E1] text-primary font-bold"
                                  : "text-gray-700 hover:bg-[#EFF8E1]/60 hover:text-primary"
                              }`}
                            >
                              <span className="truncate">{cert}</span>
                              {isSelected && (
                                <CheckIcon
                                  size={15}
                                  className="text-primary shrink-0 ml-2"
                                />
                              )}
                            </button>
                          );
                        })}
                      </div>
                    )}
                  </div>
                </div>

                {/* 5. Trade Memberships Filter */}
                <div className="flex flex-col gap-1.5 relative">
                  <label className="text-xs font-bold text-gray-700">
                    Trade Association
                  </label>
                  <div className="relative">
                    <button
                      type="button"
                      onClick={() =>
                        setActiveDropdown(
                          activeDropdown === "membership"
                            ? null
                            : "membership",
                        )
                      }
                      className={`w-full flex items-center justify-between pl-4 pr-3.5 py-3 rounded-xl text-sm font-medium transition-all duration-200 text-left cursor-pointer focus:outline-none focus:ring-2 focus:ring-primary/20 ${
                        selectedMembership
                          ? "bg-[#EFF8E1] border-2 border-primary text-primary font-bold shadow-xs"
                          : "bg-white border border-gray-200 text-gray-800 hover:border-primary/60 hover:bg-gray-50/50 shadow-2xs"
                      }`}
                    >
                      <span className="truncate">
                        {selectedMembership || "All Trade Associations"}
                      </span>
                      <ChevronDownIcon
                        size={16}
                        className={`shrink-0 ml-2 transition-transform duration-300 ${
                          activeDropdown === "membership"
                            ? "rotate-180 text-primary"
                            : selectedMembership
                              ? "text-primary"
                              : "text-gray-400"
                        }`}
                      />
                    </button>

                    {activeDropdown === "membership" && (
                      <div className="absolute top-full right-0 lg:left-auto lg:right-0 mt-2 w-full min-w-[260px] sm:min-w-[280px] md:min-w-[340px] max-w-md z-50 bg-white border border-[#467302]/30 rounded-2xl shadow-2xl p-1.5 max-h-72 overflow-y-auto">
                        <button
                          type="button"
                          onClick={() => {
                            setSelectedMembership(null);
                            setActiveDropdown(null);
                          }}
                          className={`w-full px-3.5 py-2.5 rounded-xl text-left text-sm flex items-center justify-between cursor-pointer transition-colors ${
                            selectedMembership === null
                              ? "bg-[#EFF8E1] text-primary font-bold"
                              : "text-gray-700 hover:bg-[#EFF8E1]/60 hover:text-primary"
                          }`}
                        >
                          <span>All Trade Associations</span>
                          {selectedMembership === null && (
                            <CheckIcon
                              size={15}
                              className="text-primary shrink-0 ml-2"
                            />
                          )}
                        </button>
                        {memberships.map((mem) => {
                          const isSelected = selectedMembership === mem;
                          return (
                            <button
                              key={`mem-${mem}`}
                              type="button"
                              onClick={() => {
                                setSelectedMembership(mem);
                                setActiveDropdown(null);
                              }}
                              className={`w-full px-3.5 py-2.5 rounded-xl text-left text-sm flex items-center justify-between cursor-pointer transition-colors ${
                                isSelected
                                  ? "bg-[#EFF8E1] text-primary font-bold"
                                  : "text-gray-700 hover:bg-[#EFF8E1]/60 hover:text-primary"
                              }`}
                            >
                              <span className="truncate">{mem}</span>
                              {isSelected && (
                                <CheckIcon
                                  size={15}
                                  className="text-primary shrink-0 ml-2"
                                />
                              )}
                            </button>
                          );
                        })}
                      </div>
                    )}
                  </div>
                </div>
              </div>

              {/* Quick Actions inside filter box */}
              {activeFilterCount > 0 && (
                <div className="mt-3.5 pt-3 border-t border-[#467302]/20 flex items-center justify-between text-xs">
                  <span className="text-gray-600 font-medium">
                    {filteredMills.length} matching mills found
                  </span>
                  <button
                    onClick={() => {
                      setSelectedProvince(null);
                      setSelectedCity(null);
                      setSelectedRiceProduct(null);
                      setSelectedCertification(null);
                      setSelectedMembership(null);
                    }}
                    className="text-primary font-bold hover:underline cursor-pointer"
                  >
                    Clear all filters
                  </button>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Active Filter Badges */}
      {activeFilterCount > 0 && (
        <div className="mb-6 flex flex-wrap items-center gap-2">
          <span className="text-xs font-bold text-gray-500 mr-1">
            Active Filters:
          </span>
          {selectedProvince && (
            <span className="inline-flex items-center gap-1.5 bg-[#EFF8E1] text-primary border border-primary/20 text-xs px-3 py-1 rounded-full font-medium">
              <span>Province: {selectedProvince}</span>
              <button
                onClick={() => {
                  setSelectedProvince(null);
                  setSelectedCity(null);
                }}
                className="hover:text-red-600 cursor-pointer"
              >
                <XIcon size={12} />
              </button>
            </span>
          )}
          {selectedCity && (
            <span className="inline-flex items-center gap-1.5 bg-[#EFF8E1] text-primary border border-primary/20 text-xs px-3 py-1 rounded-full font-medium">
              <span>City: {selectedCity}</span>
              <button
                onClick={() => setSelectedCity(null)}
                className="hover:text-red-600 cursor-pointer"
              >
                <XIcon size={12} />
              </button>
            </span>
          )}
          {selectedRiceProduct && (
            <span className="inline-flex items-center gap-1.5 bg-[#EFF8E1] text-primary border border-primary/20 text-xs px-3 py-1 rounded-full font-medium">
              <span>Rice: {selectedRiceProduct}</span>
              <button
                onClick={() => setSelectedRiceProduct(null)}
                className="hover:text-red-600 cursor-pointer"
              >
                <XIcon size={12} />
              </button>
            </span>
          )}
          {selectedCertification && (
            <span className="inline-flex items-center gap-1.5 bg-[#EFF8E1] text-primary border border-primary/20 text-xs px-3 py-1 rounded-full font-medium">
              <span>Cert: {selectedCertification}</span>
              <button
                onClick={() => setSelectedCertification(null)}
                className="hover:text-red-600 cursor-pointer"
              >
                <XIcon size={12} />
              </button>
            </span>
          )}
          {selectedMembership && (
            <span className="inline-flex items-center gap-1.5 bg-[#EFF8E1] text-primary border border-primary/20 text-xs px-3 py-1 rounded-full font-medium">
              <span>Membership: {selectedMembership}</span>
              <button
                onClick={() => setSelectedMembership(null)}
                className="hover:text-red-600 cursor-pointer"
              >
                <XIcon size={12} />
              </button>
            </span>
          )}
          <button
            onClick={clearAllFilters}
            className="text-xs text-primary font-semibold hover:underline ml-1 cursor-pointer"
          >
            Clear all
          </button>
        </div>
      )}

      {/* Results Count Header */}
      <div className="flex items-center justify-between mb-8 pb-4 border-b border-gray-100">
        <p className="text-sm text-gray-600">
          Showing{" "}
          <span className="font-bold text-primary">
            {displayedMills.length}
          </span>{" "}
          of{" "}
          <span className="font-bold text-gray-900">
            {filteredMills.length}
          </span>{" "}
          mills
          {filteredMills.length < mills.length && ` (filtered from ${mills.length})`}
        </p>
      </div>

      {/* Mills Grid */}
      {displayedMills.length > 0 ? (
        <>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-7">
            {displayedMills.map((mill, millIndex) => (
              <Link
                key={`mill-card-${millIndex}-${mill.slug}`}
                href={`/mills/${mill.slug}`}
                className="group border border-gray-200 rounded-2xl p-7 hover:border-primary hover:-translate-y-2 transition-all duration-500 hover:shadow-xl bg-white flex flex-col justify-between"
              >
                <div>
                  {/* Location Tag */}
                  {mill.locationSummary && (
                    <div className="flex items-center gap-1.5 text-xs text-primary font-semibold mb-2.5">
                      <MapPinIcon size={13} className="shrink-0 text-accent" />
                      <span>{mill.locationSummary}</span>
                    </div>
                  )}

                  {/* Mill Title */}
                  <div className="mb-4">
                    <Heading
                      as="h3"
                      variant="card"
                      className="text-primary group-hover:text-accent transition-colors"
                    >
                      {mill.name}
                    </Heading>
                  </div>

                  {/* Certifications Badge Pills */}
                  {mill.certifications.length > 0 && (
                    <div className="flex flex-wrap gap-1.5 mb-5">
                      {mill.certifications.slice(0, 3).map((cert, certIdx) => (
                        <span
                          key={`mill-cert-${mill.slug}-${certIdx}-${cert}`}
                          className="bg-primary/10 text-primary text-xs px-2.5 py-1 rounded-full font-medium"
                        >
                          {cert}
                        </span>
                      ))}
                      {mill.certifications.length > 3 && (
                        <span
                          key={`mill-cert-overflow-${mill.slug}`}
                          className="bg-gray-100 text-gray-600 text-xs px-2.5 py-1 rounded-full font-medium"
                        >
                          +{mill.certifications.length - 3} more
                        </span>
                      )}
                    </div>
                  )}

                  {/* Key Details List */}
                  <div className="space-y-2.5 text-sm text-gray-600 border-t border-gray-100 pt-4">
                    {/* Milling / Storage Capacity */}
                    {mill.millingCapacitySummary && (
                      <div className="flex items-start gap-2.5">
                        <FactoryIcon
                          size={16}
                          className="text-primary shrink-0 mt-0.5"
                        />
                        <div>
                          <span className="font-semibold text-gray-800">
                            Capacity:
                          </span>{" "}
                          <span>{mill.millingCapacitySummary}</span>
                        </div>
                      </div>
                    )}

                    {/* Rice Varieties */}
                    {mill.riceProducts.length > 0 && (
                      <div className="flex items-start gap-2.5">
                        <WheatIcon
                          size={16}
                          className="text-accent shrink-0 mt-0.5"
                        />
                        <div>
                          <span className="font-semibold text-gray-800">
                            Products:
                          </span>{" "}
                          <span>
                            {mill.riceProducts.slice(0, 3).join(", ")}
                            {mill.riceProducts.length > 3 &&
                              ` +${mill.riceProducts.length - 3} more`}
                          </span>
                        </div>
                      </div>
                    )}

                    {/* Export Destinations */}
                    {mill.exportDestinations.length > 0 && (
                      <div className="flex items-start gap-2.5">
                        <GlobeIcon
                          size={16}
                          className="text-accent shrink-0 mt-0.5"
                        />
                        <div>
                          <span className="font-semibold text-gray-800">
                            Exports:
                          </span>{" "}
                          <span>
                            {mill.exportDestinations.slice(0, 3).join(", ")}
                            {mill.exportDestinations.length > 3 &&
                              ` +${mill.exportDestinations.length - 3} more`}
                          </span>
                        </div>
                      </div>
                    )}
                  </div>
                </div>

                {/* Card Footer CTA */}
                <div className="mt-6 pt-4 border-t border-gray-100 flex items-center justify-between">
                  <span className="text-sm font-bold text-primary group-hover:text-accent transition-colors flex items-center gap-2">
                    View Mill Profile
                  </span>
                  <span className="w-8 h-8 rounded-full bg-primary/10 text-primary flex items-center justify-center group-hover:bg-primary group-hover:text-white transition-all duration-300">
                    <ArrowRightIcon size={16} />
                  </span>
                </div>
              </Link>
            ))}
          </div>

          {/* Load More Button */}
          {hasMore && (
            <div className="mt-14 text-center">
              <button
                onClick={() => setVisibleCount((prev) => prev + PAGE_SIZE)}
                className="bg-white border-2 border-primary text-primary hover:bg-primary hover:text-white font-bold py-3.5 px-8 rounded-full transition-all duration-300 shadow-xs hover:shadow-md cursor-pointer"
              >
                Load More Mills ({filteredMills.length - visibleCount} remaining)
              </button>
            </div>
          )}
        </>
      ) : (
        <div className="text-center py-20 bg-gray-50 rounded-2xl border border-gray-100">
          <p className="text-gray-600 text-lg font-medium">
            No rice mills found matching your filter criteria.
          </p>
          <p className="text-gray-400 text-sm mt-1">
            Try searching a different city, variety, or clearing active filters.
          </p>
          <button
            onClick={clearAllFilters}
            className="mt-5 inline-block bg-primary text-white px-6 py-2.5 rounded-full font-semibold text-sm hover:bg-accent transition-all duration-300 cursor-pointer"
          >
            Clear All Filters
          </button>
        </div>
      )}
    </div>
  );
}
