"use client";

import { useEffect, useRef, useState } from "react";
import { Swiper, SwiperSlide } from "swiper/react";
import { FreeMode, Navigation } from "swiper/modules";
import "swiper/css";
import "swiper/css/navigation";
import Image from "next/image";
import { IoCheckmarkCircle } from "react-icons/io5";
import SideDrawer from "./common/SideDrawer";
import Button from "./common/Button";
import { IoLocationOutline } from "react-icons/io5";
import Select from "react-select";
import Link from "next/link";
import { getSubCategories } from "@/lib/actions/productCategoryAction";
import { useLocale } from "next-intl";
import { useTranslations } from "next-intl";
import { getImageUrl } from "@/hooks/useImageUrl";
import { useRouter } from "next/navigation";
import { useSelectTheme } from "@/hooks/useSelectTheme";
import SecureAddressAutocomplete from "./SecureAddressAutocomplete";

export interface Category {
  id: string;
  name: string;
  image: string;
  parent_category_slug?: string;
  slug: string;
  description?: string;
}

interface Props {
  categories: Category[];
  isOpen: boolean;
  onClose: () => void;
  initialMainCategoryId?: string | null;
  initialMainCategoryIndex?: number | null;
}

export default function CategorySliderSideDrawer({
  categories,
  isOpen,
  onClose,
  initialMainCategoryId = null,
  initialMainCategoryIndex = null,
}: Props) {
  const t = useTranslations();
  const [selectedMainCategoryId, setSelectedMainCategoryId] = useState<string | null>(null);
  const [subCategories, setSubCategories] = useState<any[]>([]);
  const [selectedSubCategoryIds, setSelectedSubCategoryIds] = useState<string[]>([]);
  const locale = useLocale();
  const router = useRouter();
  const [latitude, setLatitude] = useState<number | null>(null);
  const [longitude, setLongitude] = useState<number | null>(null);
 const handleAddressAutofill = (addressData: any) => {
  if (!addressData) return;

  if (addressData.latitude) {
    setLatitude(addressData.latitude);
  }

  if (addressData.longitude) {
    setLongitude(addressData.longitude);
  }
};

  // When drawer opens, pre-select initialMainCategoryId if provided
  useEffect(() => {
    if (isOpen) {
      setSelectedMainCategoryId(initialMainCategoryId || null);
      setSelectedSubCategoryIds([]);
    }

  }, [isOpen, initialMainCategoryId]);

  // Fetch subcategories for the selected main category
  useEffect(() => {
    async function fetchSubCategories() {
      if (!selectedMainCategoryId) {
        setSubCategories([]);
        return;
      }
      try {
        const data = await getSubCategories(selectedMainCategoryId);
        setSubCategories(data.data || []);
      } catch {
        setSubCategories([]);
      }
    }
    fetchSubCategories();
  }, [selectedMainCategoryId, locale]);

  // Single-select handler for main categories
  const handleMainCategoryToggle = (cat: any) => {
    setSelectedMainCategoryId(cat.id);
    setSelectedSubCategoryIds([]);
  };

  // Multi-select handler for subcategories
  const handleSubCategoryToggle = (sub: any) => {
    setSelectedSubCategoryIds((prev) => {
      const isSelected = prev.includes(sub.id);
      if (isSelected) {
        return prev.filter((id) => id !== sub.id);
      } else {
        return [...prev, sub.id];
      }
    });
  };

  const prevRef = useRef<HTMLButtonElement | null>(null);
  const nextRef = useRef<HTMLButtonElement | null>(null);
  const [swiperInstance, setSwiperInstance] = useState<any>(null);

  // Scroll to selected category when drawer opens
  useEffect(() => {
    if (isOpen && swiperInstance) {
      const timer = setTimeout(() => {
        if (
          typeof initialMainCategoryIndex === "number" &&
          initialMainCategoryIndex >= 0
        ) {
          swiperInstance.slideTo(initialMainCategoryIndex);
        } else {
          swiperInstance.slideTo(0);
        }
      }, 100);
      return () => clearTimeout(timer);
    }
  }, [isOpen, swiperInstance, initialMainCategoryIndex]);

  const categoryReasons = [
    { value: "gift_purpose", label: t("category_drawer.category_reasons.gift_purpose") },
    { value: "discount_offer", label: t("category_drawer.category_reasons.discount_offer") },
    { value: "recommended", label: t("category_drawer.category_reasons.recommended") },
    { value: "business_need", label: t("category_drawer.category_reasons.business_need") },
    { value: "exploration", label: t("category_drawer.category_reasons.exploration") },
  ];


  const { themeKey, isDarkMode, customStyles } = useSelectTheme();




  // Helper: get heading for each level
  const getHeadingForLevel = (level: number) => {
    if (level === 0) return "Subcategories";
    return "Sub-" + "sub".repeat(level) + "categories";
  };

  // Flattened multi-level rendering
  const renderSubcategoryLevels = (initialSubCategories: any[]) => {
    let levels: any[][] = [];
    let parentTitles: string[] = [];
    let currentLevel = initialSubCategories;
    let selectedIds = selectedSubCategoryIds;
    let level = 0;
    let lastParentTitle = categories.find((cat) => cat.id === selectedMainCategoryId)?.name || "Subcategories";
    while (currentLevel && currentLevel.length > 0) {
      levels.push(currentLevel);
      parentTitles.push(lastParentTitle);
      let selectedItem = currentLevel.find((item: any) => selectedIds.includes(item.id));
      lastParentTitle = selectedItem ?
        (selectedItem.title[locale] || selectedItem.title.en || selectedItem.title.ar)
        : lastParentTitle;

      const nextLevel: any[] = [];
      for (const item of currentLevel) {
        if (
          selectedIds.includes(item.id) &&
          item.children &&
          item.children.length > 0
        ) {
          nextLevel.push(...item.children);
        }
      }
      if (nextLevel.length === 0) break;
      currentLevel = nextLevel;
      level++;
    }
    return levels.map((subCategories, idx) => (
      <div key={idx} className={idx === 0 ? "mt-6" : "mt-2"}>
        {/* Parent element's title as heading */}
        <p className="block text-xs font-normal text-neutrals500 mb-1 dark:text-neutrals400">
          {parentTitles[idx] || "Subcategories"}
        </p>
        {/* Blue separator with dynamic alignment for first level */}

        <div className="w-full mb-4 relative h-2">
          <div className="absolute left-0 top-0 h-1 bg-neutrals200 rounded-full w-full" />
          {selectedIds.length > 0 ? (
            <div
              className="absolute top-0 h-1 bg-primary800 rounded-full transition-all duration-200"
              style={{ left: 0, width: '25%' }}
            />
          ) : null}
        </div>

        <div className="flex flex-row flex-wrap gap-3 overflow-x-auto">
          {subCategories.map((sub) => {
            const isChecked = selectedSubCategoryIds.includes(sub.id);
            return (
              <div key={sub.id} className="flex flex-col items-center">
                <button
                  onClick={async () => {
                    handleSubCategoryToggle(sub);
                    if (typeof sub.children === "undefined" && !isChecked) {
                      const data = await getSubCategories(sub.id);
                      sub.children = data.data || [];
                      setSubCategories((prev: any[]) => [...prev]);
                    }
                  }}
                  className={`px-4 py-2 flex items-center gap-2 rounded-md text-sm border ${isChecked
                    ? "bg-neutrals50 text-primary500"
                    : "bg-white text-neutrals800 border-neutrals200 dark:bg-card dark:border-darkborder dark:text-neutrals400"
                    }`}
                >
                  <img
                    src={getImageUrl(sub.category_image?.file_path || sub.category_icon?.file_path || sub.image, false, "/categories/electronic.webp")}
                    alt={sub.title[locale]}
                    width={24}
                    height={24}
                    className="object-contain rounded-full mr-2"
                    style={{ minWidth: 24, minHeight: 24 }}
                    onError={(e) => {
                      e.currentTarget.onerror = null;
                      e.currentTarget.src = "/default.jpg";
                    }}
                  />
                  {sub.title[locale]}
                  {isChecked && (
                    <IoCheckmarkCircle className="text-primary500 text-xl ml-2" />
                  )}
                </button>
              </div>
            );
          })}
        </div>
      </div>
    ));
  };

  const handleApplyClick = () => {

    const selectedMainCategory = categories.find(cat => cat.id === selectedMainCategoryId);

    const getAllSelectedSubcategories = (subCats: any[]): any[] => {
      let allSelected: any[] = [];

      subCats.forEach(subCat => {
        if (selectedSubCategoryIds.includes(subCat.id)) {
          allSelected.push(subCat);

          // Recursively get selected children
          if (subCat.children && subCat.children.length > 0) {
            const selectedChildren = getAllSelectedSubcategories(subCat.children);
            allSelected = [...allSelected, ...selectedChildren];
          }
        }
      });

      return allSelected;
    };
    const selectedSubCategories = getAllSelectedSubcategories(subCategories);

    let parentSlug = selectedMainCategory?.parent_category_slug;

    // if(parentSlug?.includes("community")) {
    //   parentSlug = "community";
    // } else if(parentSlug?.includes("service")) {
    //   parentSlug = "service";
    // }

    let url = `/filters/${parentSlug}?category=${selectedMainCategory?.slug}`;

    if (selectedSubCategories.length > 0) {
      let lastItem = selectedSubCategories[selectedSubCategories.length - 1];
      url = `/filters/${selectedMainCategory?.parent_category_slug}?category=${lastItem.slug}`;
    }
    // ✅ ADD LOCATION PARAMS CONDITIONALLY
      const params = new URLSearchParams();

      params.set(
        "category",
        selectedSubCategories.length > 0
          ? selectedSubCategories[selectedSubCategories.length - 1].slug
          : selectedMainCategory?.slug || ""
      );

      if (latitude !== null) {
        params.set("latitude", String(latitude));
      }

      if (longitude !== null) {
        params.set("longitude", String(longitude));
      }

      router.push(`/filters/${parentSlug}?${params.toString()}`);
    // router.push(url);
    onClose();
  }

  return (
    <SideDrawer
      isOpen={isOpen}
      title={t("category_drawer.title")}
      onClose={onClose}
      footer={
        <div className="flex justify-end gap-2">
          <Button type="submit" onClick={handleApplyClick} label={t("category_drawer.apply")} variant="secondary" />
        </div>
      }
    >
      <div className="relative">
        <div className="relative">
          <Swiper
            dir="auto"
            spaceBetween={16}
            modules={[FreeMode, Navigation]}
            freeMode={true}
            navigation={{
              prevEl: prevRef.current,
              nextEl: nextRef.current,
            }}
            onBeforeInit={(swiper: any) => {
              swiper.params.navigation.prevEl = prevRef.current;
              swiper.params.navigation.nextEl = nextRef.current;
            }}
            onSwiper={(swiper) => setSwiperInstance(swiper)}
            breakpoints={{
              320: { slidesPerView: 4, spaceBetween: 10 },
              640: { slidesPerView: 5 },
              768: { slidesPerView: 7 },
              1024: { slidesPerView: 7 },
              1280: { slidesPerView: 8 },
            }}
            className="px-6"
          >
            {categories.map((cat, index) => {
              const isChecked = selectedMainCategoryId === cat.id;
              return (
                <SwiperSlide key={index}>
                  <label className="relative group flex flex-col items-center text-center cursor-pointer">
                    <div className="w-[60px] h-[60px] relative rounded-full flex items-center justify-center mb-2.5 bg-kzlightblue dark:bg-card">
                      <input
                        type="checkbox"
                        className="sr-only"
                        checked={isChecked}
                        onChange={() => handleMainCategoryToggle(cat)}
                      />
                      <img
                        src={getImageUrl(cat.image, false, "/categories/electronic.webp")}
                        alt={cat.name}
                        width={60}
                        height={60}
                        className="object-cover w-[60px] h-[60px] rounded-full"
                        loading="lazy"
                        onError={(e) => {
                          e.currentTarget.onerror = null;
                          e.currentTarget.src = "/default.jpg";
                        }}
                      />
                      {isChecked && (
                        <span className="absolute top-1.5 -right-0 text-lg text-primary500 dark:text-primary400">
                         <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
                          <g clipPath="url(#clip0_3867_5674)">
                          <rect width="12" height="12" rx="6" fill="white"/>
                          <path d="M6 0C2.69163 0 0 2.69163 0 6C0 9.30837 2.69163 12 6 12C9.30837 12 12 9.30837 12 6C12 2.69163 9.30837 0 6 0ZM9.1226 3.98913L5.24567 8.60452C5.20315 8.65517 5.15023 8.6961 5.09051 8.72451C5.03078 8.75293 4.96565 8.76818 4.89952 8.76923H4.89173C4.82704 8.76921 4.76308 8.75559 4.70399 8.72925C4.6449 8.70291 4.59201 8.66444 4.54875 8.61635L2.88721 6.77019C2.84501 6.72544 2.81219 6.6727 2.79067 6.61507C2.76914 6.55745 2.75935 6.49611 2.76188 6.43465C2.7644 6.37319 2.77918 6.31285 2.80536 6.25719C2.83153 6.20152 2.86857 6.15165 2.91429 6.1105C2.96001 6.06936 3.0135 6.03776 3.07161 6.01758C3.12971 5.9974 3.19127 5.98904 3.25265 5.99299C3.31404 5.99694 3.37401 6.01312 3.42906 6.04058C3.4841 6.06803 3.5331 6.10622 3.57317 6.15288L4.87962 7.60442L8.41587 3.39548C8.49519 3.30377 8.60741 3.24696 8.72828 3.23733C8.84915 3.2277 8.96896 3.26602 9.0618 3.34401C9.15465 3.422 9.21307 3.53339 9.22445 3.65411C9.23582 3.77483 9.19924 3.89517 9.1226 3.98913Z" fill="currentColor"/>
                          </g>
                          <defs>
                          <clipPath id="clip0_3867_5674">
                          <rect width="12" height="12" rx="6" fill="white"/>
                          </clipPath>
                          </defs>
                          </svg>

                        </span>
                      )}
                    </div>
                    <p
                      className={`text-xs font-normal ${isChecked
                        ? "text-primary900 dark:text-neutrals400"
                        : "text-neutrals800 dark:text-neutrals400"
                        }`}
                    >
                      {cat.name}
                    </p>
                  </label>
                </SwiperSlide>
              );
            })}
          </Swiper>

          <button
            ref={prevRef}
            className="group absolute left-0 top-1/2 -translate-y-1/2 z-10 bg-white dark:bg-darkbg dark:border-darkborder p-1 h-8 w-8 flex items-center justify-center rounded-lg border border-neutrals100 hover:shadow-headerShadow"
            style={{ marginLeft: "2px" }}
          >
            <svg
              width="20"
              height="20"
              viewBox="0 0 24 24"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path
                d="M14.7054 17.2946C15.0947 16.9053 15.095 16.2743 14.7062 15.8846L11.5348 12.7063C11.1453 12.316 11.1453 11.684 11.5348 11.2937L14.7062 8.11538C15.095 7.72569 15.0947 7.09466 14.7054 6.70538C14.3158 6.31581 13.6842 6.31581 13.2946 6.70538L8.70711 11.2929C8.31658 11.6834 8.31658 12.3166 8.70711 12.7071L13.2946 17.2946C13.6842 17.6842 14.3158 17.6842 14.7054 17.2946Z"
                fill="#64748B"
                className="transition-colors duration-200 group-hover:fill-primary500 dark:group-hover:fill-white"
              />
            </svg>
          </button>
          <button
            ref={nextRef}
            className="group absolute right-0 top-1/2 -translate-y-1/2 z-10 bg-white dark:bg-darkbg dark:border-darkborder p-1 h-8 w-8 flex items-center justify-center rounded-lg border border-neutrals100 hover:shadow-headerShadow"
            style={{ marginRight: "2px" }}
          >
            <svg
              width="20"
              height="20"
              viewBox="0 0 24 24"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path
                d="M9.29446 17.2946C8.90519 16.9053 8.90484 16.2743 9.29369 15.8846L12.465 12.7063C12.8545 12.316 12.8545 11.684 12.465 11.2937L9.29369 8.11538C8.90484 7.72569 8.90519 7.09466 9.29446 6.70538C9.68403 6.31581 10.3157 6.31581 10.7052 6.70538L15.2927 11.2929C15.6833 11.6834 15.6833 12.3166 15.2927 12.7071L10.7052 17.2946C10.3157 17.6842 9.68403 17.6842 9.29446 17.2946Z"
                fill="#64748B"
                className="transition-colors duration-200 group-hover:fill-primary500 dark:group-hover:fill-white"
              />
            </svg>
          </button>
        </div>

        {selectedMainCategoryId && subCategories.length > 0 && renderSubcategoryLevels(subCategories)}

        <div className="mt-5">
          {/* <span className="text-sm block text-primary500 mb-2.5 dark:text-primary400">

            {t("category_drawer.sort_by")}:

          </span>
          <div className="mb-2.5">
            <label
              htmlFor="reason"
              className="block text-xs font-normal text-neutrals500 mb-1 dark:text-neutrals400"
            >
              {t("category_drawer.region")}
            </label>
            <Select
              id="reason"
              styles={customStyles}
              key={themeKey}
              options={categoryReasons}
              placeholder="Select"
              className="react-select-container"
              classNamePrefix="react-select"
            />
          </div> */}
          <div className="flex items-center">
            <div className="bg-neutrals200 p-2 rounded-md dark:bg-card">
              <IoLocationOutline className="text-primary500 text-xl dark:text-primary400" />
            </div>
            <Link
              href=""
              className="text-base max-sm:text-sm ml-3 font-semibold text-primary500 underline dark:text-primary400 rtl:mr-3 rtl:ml-0"
            >

              {t("category_drawer.near_by")}
            </Link>
          </div>
        </div>
      </div>
      <br/>
        <div className="bg-blue-50 dark:bg-blue-900/20 p-4 rounded-lg border border-blue-200 dark:border-blue-800">
                    <label className="block text-sm font-semibold mb-2 text-gray-900 dark:text-white">
                      🔍 {t("search_address")}
                    </label>

                    <SecureAddressAutocomplete
                      label={t("search_address")}
                      placeholder={t("start_type_address")}
                      onChange={handleAddressAutofill}
                    />

           </div>
    </SideDrawer>
    
  );
}
