"use client";

import { useState, useEffect } from "react"
import Image from "next/image";
import { withCDN } from "@/src/lib/utils";
import { ChevronDown, Loader2 } from "lucide-react"; // Import Loader2 here
import { fetchClassesAction } from "@/src/lib/actions/classesAction";
import { transformClasses, buildFilterOptions, filterClasses, ALL_FILTER_OPTION } from "@/src/lib/utils/classesMapper";
import type { ClassListingItem } from "@/src/lib/types/classes";
import type { TenantData } from "@/src/lib/types/header";
import ClassListingCardSkeleton from "../ui/skeletons/ClassListingCardSkeleton";
import { useSelectedClass } from "@/src/lib/context/SelectedClassContext";
import { useLocalizedNavigation } from "@/src/lib/hooks/useLocalizedNavigation"; 
import { useSearchParams } from "next/navigation";

function CustomDropdown({
  label,
  options,
  value,
  onChange,
  onClear,
  isOpen,
  onToggle,
}: {
  label: string
  options: string[]
  value: string
  onChange: (val: string) => void
  onClear: () => void
  isOpen: boolean
  onToggle: () => void
}) {
  const isPlaceholder = value === options[0]

  return (
    <div className="relative min-w-[160px] sm:col-span-3">
      {/* Trigger */}
     <button
         type="button"
         onClick={onToggle}
         className={`
          w-full flex items-center justify-between
          px-4 py-3 text-sm bg-white
         focus:outline-none focus:ring-0
         border border-[#58585A]
       ${
        isOpen
           ? "rounded-t-[20px] rounded-b-none border-b-0"
           : "rounded-full"
         }
       ${
         isPlaceholder
           ? "text-[#828282]"
           : "text-[#58585A]"
          }
         `}
     >
        <span className="truncate whitespace-nowrap overflow-hidden max-w-[90%]">{value}</span>

        {/* Clear button (X) */}
        {!isPlaceholder && (
          <div
            onClick={(e) => {
              e.stopPropagation()
              onClear()
            }}
            className="flex items-center justify-center w-5 h-5 ml-2 text-[#828282] hover:text-[#58585A] hover:bg-gray-200 rounded-full transition-colors text-lg leading-none cursor-pointer"
            role="button"
            tabIndex={0}
            aria-label="Clear filter"
            onKeyDown={(e) => {
              if (e.key === 'Enter' || e.key === ' ') {
                e.stopPropagation()
                onClear()
              }
            }}
          >
            ✕
          </div>
        )}

        {/* Arrow */}
        {isPlaceholder && (
          <ChevronDown
            className={`w-4 h-4 transition-transform ${
              isOpen ? "rotate-180" : ""
            }`}
          />
        )}
      </button>

      {/* Dropdown */}
      {isOpen && (
        <div className="absolute left-0 right-0 mt-1 z-20 rounded-2xl border border-[#58585A] bg-white shadow-lg overflow-hidden class-registration-box">
          <ul className="text-sm mb-[7px] rounded-[12px] rounded-tl-[0px] rounded-tr-[0px] bg-white overflow:hidden">
            {/* "All" — clears this filter (shows every class for this dimension) */}
            <li
              key={ALL_FILTER_OPTION}
              onClick={() => {
                onChange(ALL_FILTER_OPTION)
                onToggle()
              }}
              className={`
                px-4 py-3 cursor-pointer
                ${value === ALL_FILTER_OPTION ? "text-[#58585A] bg-blue-10" : "text-[#58585A]"}
                hover:bg-gray-100
              `}
            >
              {ALL_FILTER_OPTION}
            </li>
            {options.slice(1).map((option) => (
              <li
                key={option}
                onClick={() => {
                  onChange(option)
                  onToggle()
                }}
                className={`
                  px-4 py-3 cursor-pointer
                  ${option === value ? "text-[#58585A] bg-blue-10" : "text-[#58585A]"}
                  hover:bg-gray-100
                `}
              >
                {option}
              </li>
            ))}
          </ul>
        </div>
      )}
    </div>
  )
}

export default function ClassListing({ tenant, hideRegisterButton = false }: { tenant?: TenantData; hideRegisterButton?: boolean }) {
  const router = useLocalizedNavigation();
  const searchParams = useSearchParams();
  const { setSelectedClass } = useSelectedClass(); 
  const franchiseeIdFromUrl = searchParams.get("franchiseeId");

  // State management
  const [allClasses, setAllClasses] = useState<ClassListingItem[]>([]);
  const [rawClasses, setRawClasses] = useState<any[]>([]); 
  const [filteredClasses, setFilteredClasses] = useState<ClassListingItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [openDropdown, setOpenDropdown] = useState<string | null>(null);
  const [values, setValues] = useState<Record<string, string>>({});
  const [visibleMobileCount, setVisibleMobileCount] = useState(4);
  const [filters, setFilters] = useState<Record<string, string[]>>({});
  
  // Track which item is navigating to show loader
  const [navigatingId, setNavigatingId] = useState<number | null>(null);

  // Fetch classes on component mount
  useEffect(() => {
    const loadClasses = async () => {
      try {
        setLoading(true);
        setError(null);

        const response = await fetchClassesAction(tenant?.zoho_franchise_id, franchiseeIdFromUrl);

        if (!response.success || response.data.length === 0) {
          setError(response.message || "No classes available");
          setAllClasses([]);
          setRawClasses([]); 
          setFilteredClasses([]);
          setFilters({});
          return;
        }

        setRawClasses(response.data); 

        // Transform API data to UI format
        const transformedClasses = transformClasses(response.data);
        setAllClasses(transformedClasses);
        setFilteredClasses(transformedClasses);

        // Build filter options from data
        const filterOptions = buildFilterOptions(transformedClasses);
        setFilters(filterOptions);
      } catch (err) {
        const errorMessage = err instanceof Error ? err.message : "Failed to load classes";
        setError(errorMessage);
        console.error("[ClassListing] Error loading classes:", err);
      } finally {
        setLoading(false);
      }
    };

    loadClasses();
  }, []);

  // Apply filters whenever values or allClasses change
  useEffect(() => {
    if (allClasses.length === 0) {
      setFilteredClasses([]);
      return;
    }

    const filtered = filterClasses(allClasses, values);
    setFilteredClasses(filtered);
    setVisibleMobileCount(4);
  }, [values, allClasses]);

  const handleRegister = (item: ClassListingItem) => {
    // Set loading state for this specific button
    setNavigatingId(item.id);
    // Append #registration-form so the target page knows to scroll
    router.push(`/class-registration/${item.id}#auto-scroll`);
  };

  // Build filter configuration
  const filterConfig = Object.entries(filters).map(([label, options]) => ({
    label,
    options: options || [label],
  }));

  const MOBILE_STEP = 4;

  if (loading) return <ClassListingCardSkeleton />

  if (error && allClasses.length === 0) {
    return (
      <main className="w-full px-0 pt-20 pb-[30px] md:pb-[80px] flex flex-col items-center justify-center min-h-[400px]">
        <div className="text-center relative z-[30] flex flex-col items-center">
          <h3 className="text-[30px] md:text-[40px] font-bold text-[#58585A] font-signika mb-2 uppercase leading-tight">
            No Classes Found
          </h3>
          <button
            type="button" 
            onClick={() => window.location.reload()}
            className="relative z-[50] pointer-events-auto cursor-pointer px-8 py-3 bg-[#0097DC] text-white rounded-full hover:bg-[#0088C6] transition-colors font-signika text-[16px]"
          >
            Refresh Page
          </button>
        </div>
      </main>
    );
  }

  return (
    <main className="w-full px-5 md:px-0 py-10 min-h-[400px] max-w-[1300px] mx-auto max-[360px]:px-1">
      {/* FILTERS */}
      <div className="mb-8 grid grid-cols-1 sm:grid-cols-12 gap-4 relative z-[35]">
        {filterConfig.map((filter) => {
          const currentValue = values[filter.label] ?? filter.options[0];
          const isOpen = openDropdown === filter.label;

          return (
            <CustomDropdown
              key={filter.label}
              label={filter.label}
              options={filter.options}
              value={currentValue}
              isOpen={isOpen}
              onToggle={() => setOpenDropdown(isOpen ? null : filter.label)}
              onChange={(val) => setValues({ ...values, [filter.label]: val })}
              onClear={() => setValues({ ...values, [filter.label]: filter.options[0] })}
            />
          );
        })}
      </div>

      {filteredClasses.length > 0 && (
        <p className="mb-4 text-[20px] font-light font-signika text-[#58585A] text-center xl:text-left">
          See what we have for your child ({filteredClasses.length} classes):
        </p>
      )}

      {filteredClasses.length === 0 && (
        <div className="flex flex-col items-center justify-center w-full mt-24 mb-[100px] md:mb-[200px] min-h-[300px] relative z-[30]">
          <h3 className="text-[28px] md:text-[40px] font-bold text-[#58585A] font-signika uppercase text-center leading-tight mb-2">
            No classes found
          </h3>
          <p className="text-[16px] md:text-[18px] text-[#828282] text-center max-w-md mb-8 font-signika">
            We couldn't find any classes matching your selected filters.
          </p>
          <button
            onClick={() => setValues({})}
            className="px-8 py-3 bg-[#0097DC] text-white rounded-full hover:bg-[#0088C6] transition-colors font-signika text-[16px] cursor-pointer"
          >
            Clear Filters
          </button>
        </div>
      )}

      {/*====================DESKTOP CARDS GRID===================== */}
      {filteredClasses.length > 0 && (
  <div className="hidden md:grid grid-cols-1 gap-5 xl:grid-cols-2 custom-scrollbar scroll-thin pr-[40px] overflow-y-auto max-h-[640px] h-max relative z-[30] pb-5">
          {filteredClasses.map((item) => (
            <div
              key={item.id}
              className="relative rounded-[30px] border-2 bg-white px-5 flex items-center w-full h-[300px] gap-4 overflow-hidden"
              style={{ borderColor: item.borderColor }}
            >
              {/* Ribbon */}
              <div
                className="
                relative w-[98px] md:w-[120px]
                xl:w-[98px] min-[1600px]:!w-[100px] h-[290px]
                flex items-start justify-start flex-col
                overflow-hidden ribbon-class
                "
                style={{
                  backgroundImage: `url(${item.ribbon})`,
                  backgroundSize: "cover",
                  backgroundPosition: "center bottom",
                  top: "-9px",
                }}
              >
                <div className="relative w-[68px] h-[68px] rounded-[50%] my-[10px] bg-white mx-auto flex items-center justify-center">
                  <Image src={item.iconSrc} alt={item.title} width={68} height={68} className="object-cover w-[68px] h-[68px]" />
                </div>
                <div className="mb-[6px] px-3">
                  <p className="font-regular text-[#fff] text-[12px] leading-[14px]">Age:</p>
                  <p className="text-[#fff] text-[16px] font-bold">{item.age}</p>
                </div>
                <div className="mb-[6px] px-3">
                  <p className="font-regular text-[#fff] text-[12px]  leading-[14px]">Number of lesson:</p>
                  <p className="text-[#fff] text-[16px] font-bold">{item.lessons}</p>
                </div>
                <div className="mb-[6px] px-3 ">
                  <p className="font-regular text-[#fff] text-[12px] leading-[14px]">{item.priceLabel || "Price per lesson:"}</p>
                  <p className="text-[#fff] text-[16px] font-bold"> {item.price}</p>
                </div>
              </div>

              <div className=" relative w-full xl:w-[400px] 2xl:w-[465px] min-[1600px]:!w-[80%]">
                {/* Header */}
                <div className="flex items-center justify-between border-b border-[#D9D9D9] pb-3">
                  <div className="relative w-full 2xl:w-[310px]">
                    <h2 className="text-[30px] uppercase font-bold leading-tight" style={{ color: item.borderColor }}>{item.title}</h2>
                    <p className="text-[16px] text-[#58585A] uppercase">{item.groupName}</p>
                    <div className="flex items-center gap-1 my-[10px]">
                      <Image src={withCDN("/class-registration/Google_Maps_icon_(2020)%201.png")} alt="image" width={21} height={21} className="object-contain w-[21px] h-[21px]" />
                      <a href={item.mapUrl} target="_blank" rel="noopener noreferrer" className=" text-[14px] text-[#828282] font-semibold underline  truncate  max-w-[170px] md:max-w-[200px] block">
                        {item.address}
                      </a>
                      <a href={item.mapUrl} target="_blank" rel="noopener noreferrer">
                        <Image src={withCDN("/class-registration/icon_open_in_new.png")} alt="image" width={21} height={21} className="object-contain w-[21px] h-[21px]" />
                      </a>
                    </div>
                  </div>
                </div>

                {/* Content */}
                <div className="mt-4 grid  grid-cols-[4.5fr_4.5fr_3fr] gap-2 text-sm text-gray-700">
                  <p className=" mb-[10px]">
                    <span className="font-regular text-[#828282] text-[12px]">Study period:</span><br />
                    <span className="text-[#58585A] text-[14px]">{item.period}</span>
                  </p>
                  <p className="mb-[10px] border-l border-l-[1px] border-[#d9d9d9] pl-[10px]">
                    <span className="font-regular text-[#828282] text-[12px]">Class time:</span> <br />
                    <span className="text-[#58585A] text-[14px]">{item.time}</span>
                  </p>
                  <p className="mb-[10px] border-l border-l-[1px] pl-[10px]">
                    <span className="font-regular text-[#828282] text-[12px]">Days:</span> <br />
                    <span className="text-[#58585A] text-[14px]">{item.days}</span>
                  </p>
                </div>

                {!hideRegisterButton && (
                  <button
                    type="button"
                    onClick={() => handleRegister(item)}
                    disabled={navigatingId === item.id}
                    className={`
                      relative z-20
                      inline-flex w-full items-center gap-2 xl:py-2 xl:px-1
                      rounded-full border border-[#0097DC]
                      px-2 py-2 text-[15px] xl:text-[15px] 2xl:text-[18px] font-light
                      text-white mt-[20px] mb-[10px]
                      transition-colors justify-center uppercase hover:shadow-[10px_10px_14px_#0000000D] active:shadow-[10px_10px_14px_#0000000D]  active:bg-[#0084C1] 
                      ${navigatingId === item.id ? 'bg-[#007bb5] cursor-not-allowed' : 'bg-[#0097DC] cursor-pointer'}
                    `}
                  >
                    {navigatingId === item.id ? (
                      <Loader2 className="w-6 h-6 animate-spin text-white" />
                    ) : (
                      <Image
                        src={withCDN("/programs-page/AllPrograms/Vector.svg")}
                        alt="arrow"
                        width={26}
                        height={26}
                        className="transition-all"
                      />
                    )}
                    <span>{navigatingId === item.id ? 'Loading...' : 'Register'}</span>
                  </button>
                )}
              </div>
            </div>
          ))}
        </div>
      )}

      {/*=================Mobile-card-layout=======================*/}
      {filteredClasses.length > 0 && (
        <div className="block md:hidden grid grid-cols-1 gap-5 xl:grid-cols-2 relative z-[30]">
          {filteredClasses
            .slice(0, visibleMobileCount)
            .map((item) => (
              <div
                key={item.id}
                className="relative rounded-[30px] border-2 bg-white px-4 w-full h-max gap-4 overflow-hidden max-[365px]:px-2"
                style={{ borderColor: item.borderColor }}
              >
                <div className="relative flex items-center gap-[16px]">
                  {/* Ribbon */}
                  <div
                    className="
                    relative w-[160px] h-[320px]
                    flex items-start justify-start flex-col
                    overflow-hidden ribbon-class
                    "
                    style={{
                      backgroundImage: `url(${item.ribbon})`,
                      backgroundSize: "cover",
                      backgroundPosition: "center bottom",
                      top: "-4px",
                    }}
                  >
                    <div className="relative w-[80px] h-[80px] rounded-[50%] my-[10px] bg-white mx-auto max-[365px]:w-[70px] max-[365px]:h-[70px] flex items-center justify-center">
                      <Image src={item.iconSrc} alt={item.title} width={80} height={80} className="object-contain w-[80px] h-[80px]" />
                    </div>
                    <div className="mb-[10px] px-3">
                      <p className="font-regular text-[#fff] text-[12px] leading-[14px] max-[365px]:text-[10px]">Age:</p>
                      <p className="text-[#fff] text-[16px] font-bold max-[365px]:text-[13px]">{item.age}</p>
                    </div>
                    <div className="mb-[10px] px-3">
                      <p className="font-regular text-[#fff] text-[12px]  leading-[14px] max-[365px]:text-[10px]">Number of lesson:</p>
                      <p className="text-[#fff] text-[16px] font-bold max-[365px]:text-[13px]">{item.lessons}</p>
                    </div>
                    <div className="mb-[10px] px-3">
                      <p className="font-regular text-[#fff] text-[12px] leading-[14px]">{item.priceLabel || "Price per lesson:"}</p>
                      <p className="text-[#fff] text-[16px] font-bold"> {item.price}</p>
                    </div>
                  </div>

                  <div className=" relative w-full xl:w-[400px] 2xl:w-[465px] min-[1600px]:!w-[80%] max-[365px]:w-[60%]">
                    {/* Header */}
                    <div className="flex items-center justify-between border-b border-[#D9D9D9] pb-3">
                      <div className="relative w-full">
                        <h3 className="text-[28px] uppercase font-bold leading-[30px] mb-1 max-[365px]:text-[24px] max-[365px]:leading-[28px]" style={{ color: item.borderColor }}>{item.title}</h3>
                        <p className="text-[14px] text-[#58585A] uppercase max-[365px]:text-[12px]">{item.groupName}</p>
                        <div className="flex items-center gap-1 my-[8px]">
                          <Image src={withCDN("/class-registration/google-maps_icon.png")} alt="image" width={21} height={21} className="object-contain w-[21px] h-[21px]" />
                          <a href={item.mapUrl} target="_blank" rel="noopener noreferrer" className=" text-[12px] text-[#828282] font-semibold underline  truncate  max-w-[150px] block max-[365px]:text-[11px]">
                            {item.address}
                          </a>
                        </div>
                      </div>
                    </div>

                    {/* Content */}
                    <div className="mt-4 grid grid-cols-1 text-sm text-gray-700">
                      <p className="mb-[8px]  relative pl-[18px] custom-txt">
                        <span className="font-regular text-[#828282] text-[12px] max-[365px]:text-[11px]">Study period:</span><br />
                        <span className="text-[#58585A] text-[14px] max-[365px]:text-[12px]">{item.period}</span>
                      </p>
                      <p className="mb-[8px]  relative pl-[18px] custom-txt">
                        <span className="font-regular text-[#828282] text-[12px] max-[365px]:text-[11px]">Class time:</span> <br />
                        <span className="text-[#58585A] text-[14px] max-[365px]:text-[12px]">{item.time}</span>
                      </p>
                      <p className="mb-[8px]  relative pl-[18px] custom-txt">
                        <span className="font-regular text-[#828282] text-[12px] max-[365px]:text-[11px]">Days:</span> <br />
                        <span className="text-[#58585A] text-[14px] max-[365px]:text-[12px]">{item.days}</span>
                      </p>
                    </div>
                  </div>
                </div>

                {!hideRegisterButton && (
                  <button
                    type="button"
                    onClick={() => handleRegister(item)}
                    disabled={navigatingId === item.id}
                    className={`
                      inline-flex w-full items-center gap-2 xl:py-2 xl:px-1
                      rounded-full border border-[#0097DC]
                      px-2 py-2 text-[15px] xl:text-[15px] 2xl:text-[18px] font-light
                      text-white mt-[20px] mb-[30px]
                      transition-colors justify-center uppercase hover:shadow-[10px_10px_14px_#0000000D] active:shadow-[10px_10px_14px_#0000000D]  active:bg-[#0084C1] 
                      ${navigatingId === item.id ? 'bg-[#007bb5] cursor-not-allowed' : 'bg-[#0097DC] cursor-pointer'}
                    `}
                  >
                    {navigatingId === item.id ? (
                      <Loader2 className="w-6 h-6 animate-spin text-white" />
                    ) : (
                      <Image
                        src={withCDN("/programs-page/AllPrograms/Vector.svg")}
                        alt="arrow"
                        width={26}
                        height={26}
                        className="transition-all"
                      />
                    )}
                    <span>{navigatingId === item.id ? 'Loading...' : 'Register'}</span>
                  </button>
                )}
              </div>
            ))}

          {/* ================= Load More (Mobile) ================= */}
          {visibleMobileCount < filteredClasses.length && (
            <div className="mt-6 flex justify-center md:hidden">
              <button
                onClick={() => setVisibleMobileCount((prev) => prev + MOBILE_STEP)}
                className="text-[20px] font-light text-[#0097DC] font-signika"
              >
                Load more classes
              </button>
            </div>
          )}
        </div>
      )}
    </main>
  );
}
