"use client";

import React, { useState, useEffect, useMemo } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import toast from "react-hot-toast";
import BoldIcon from "@/components/ui/BoldIcon";
import useAxios from "@/hooks/useAxios";
import { getCreateAcademyPath } from "@/lib/getCreateContentPath";
import { useTranslation } from "react-i18next";
import AcademyFilterModal, {
  AcademyFilterValues,
} from "./AcademyFilterModal";

interface AcademyFilterProps {
  onFilterChange?: (filters: Record<string, unknown>) => void;
}

interface IAcademyCategory {
  _id: string;
  title: string;
  slug: string;
  description?: string;
  icon?: string;
  color?: string;
  parent?: string | null;
  level: number;
  order: number;
  course_count: number;
  status: string;
  is_featured: boolean;
}

interface CategoryOption {
  value: string;
  label: string;
  icon?: string;
  color?: string;
}

const TOOLBAR_ICON_SIZE = 25;
const toolbarIconButtonClass =
  "inline-flex h-[25px] w-[25px] items-center justify-center shrink-0 p-0 leading-none";

const SORT_KEYS = [
  "createdAt_desc",
  "createdAt_asc",
  "likes_desc",
  "price_asc",
  "price_desc",
] as const;

const SORT_LABEL_KEYS: Record<(typeof SORT_KEYS)[number], string> = {
  createdAt_desc: "newest",
  createdAt_asc: "oldest",
  likes_desc: "popular",
  price_asc: "cheapest",
  price_desc: "priciest",
};

const TYPE_KEYS = ["", "normal", "pro", "free"] as const;

const emptyFilters: AcademyFilterValues = {
  search: "",
  category: "",
  minPrice: "",
  maxPrice: "",
  hasOffer: false,
  type: "",
  sortBy: "createdAt_desc",
};

function buildFinalFilters(filters: AcademyFilterValues) {
  let sortBy = "createdAt";
  let sortOrder = "desc";

  if (filters.sortBy === "createdAt_asc") {
    sortBy = "createdAt";
    sortOrder = "asc";
  } else if (filters.sortBy === "price_asc") {
    sortBy = "price";
    sortOrder = "asc";
  } else if (filters.sortBy === "price_desc") {
    sortBy = "price";
    sortOrder = "desc";
  } else if (filters.sortBy === "likes_desc") {
    sortBy = "likes";
    sortOrder = "desc";
  }

  return {
    search: filters.search,
    category: filters.category,
    minPrice: filters.minPrice ? Number(filters.minPrice) : undefined,
    maxPrice: filters.maxPrice ? Number(filters.maxPrice) : undefined,
    hasOffer: filters.hasOffer,
    type: filters.type,
    sortBy,
    sortOrder,
  };
}

export default function AcademyFilter({ onFilterChange }: AcademyFilterProps) {
  const { t } = useTranslation("common");
  const router = useRouter();
  const searchParams = useSearchParams();

  const sortOptions = useMemo(
    () =>
      SORT_KEYS.map((value) => ({
        value,
        label: t(`academy.filter.sort.${SORT_LABEL_KEYS[value]}`),
      })),
    [t]
  );

  const courseTypes = useMemo(
    () =>
      TYPE_KEYS.map((value) => ({
        value,
        label: t(
          value === ""
            ? "academy.filter.types.all"
            : `academy.filter.types.${value}`
        ),
      })),
    [t]
  );

  const [showFilterModal, setShowFilterModal] = useState(false);
  const [filters, setFilters] = useState<AcademyFilterValues>(emptyFilters);
  const [categories, setCategories] = useState<CategoryOption[]>([]);
  const [categoriesLoading, setCategoriesLoading] = useState(false);
  const [userType, setUserType] = useState<string | null>(null);
  const { request } = useAxios();

  const allCategoriesLabel = t("academy.filter.allCategories");

  useEffect(() => {
    setCategories([{ value: "", label: allCategoriesLabel }]);
  }, [allCategoriesLabel]);

  useEffect(() => {
    if (typeof window !== "undefined") {
      setUserType(localStorage.getItem("usertype"));
    }
  }, []);

  useEffect(() => {
    const fetchAcademyCategories = async () => {
      setCategoriesLoading(true);
      try {
        const response = await request<{ data: { docs: IAcademyCategory[] } }>(
          "GET",
          "/academy/categories?status=active&limit=100"
        );

        let categoriesList: IAcademyCategory[] = [];

        if (response?.data?.docs) {
          categoriesList = response.data.docs;
        } else if (response?.data && Array.isArray(response.data)) {
          categoriesList = response.data;
        } else if (Array.isArray(response)) {
          categoriesList = response;
        }

        const formattedCategories: CategoryOption[] = [
          { value: "", label: allCategoriesLabel },
          ...categoriesList.map((cat) => ({
            value: cat.title,
            label: cat.title,
            icon: cat.icon,
            color: cat.color,
          })),
        ];

        setCategories(formattedCategories);
      } catch (err) {
        console.log("Academy categories fetch error:", err);
      } finally {
        setCategoriesLoading(false);
      }
    };

    fetchAcademyCategories();
  }, [allCategoriesLabel, request]);

  useEffect(() => {
    setFilters({
      search: searchParams.get("search") || "",
      category: searchParams.get("category") || "",
      minPrice: searchParams.get("minPrice") || "",
      maxPrice: searchParams.get("maxPrice") || "",
      hasOffer: searchParams.get("hasOffer") === "true",
      type: searchParams.get("type") || "",
      sortBy: searchParams.get("sortBy") || "createdAt_desc",
    });
  }, [searchParams]);

  const updateURL = (newFilters: AcademyFilterValues) => {
    const params = new URLSearchParams();

    if (newFilters.search) params.set("search", newFilters.search);
    if (newFilters.category) params.set("category", newFilters.category);
    if (newFilters.minPrice) params.set("minPrice", newFilters.minPrice);
    if (newFilters.maxPrice) params.set("maxPrice", newFilters.maxPrice);
    if (newFilters.hasOffer) params.set("hasOffer", "true");
    if (newFilters.type) params.set("type", newFilters.type);
    if (newFilters.sortBy && newFilters.sortBy !== "createdAt_desc") {
      params.set("sortBy", newFilters.sortBy);
    }

    const queryString = params.toString();
    const newUrl = queryString ? `/academy?${queryString}` : "/academy";
    router.push(newUrl, { scroll: false });
  };

  const applyFilters = () => {
    updateURL(filters);
    onFilterChange?.(buildFinalFilters(filters));
    setShowFilterModal(false);
  };

  const clearFilters = () => {
    setFilters(emptyFilters);
    router.push("/academy", { scroll: false });
    onFilterChange?.({});
    setShowFilterModal(false);
  };

  const handleCreateAcademy = () => {
    if (!userType) {
      toast.error(t("academy.loginRequired"));
      return;
    }
    router.push(getCreateAcademyPath());
  };

  const activeFiltersCount = Object.values(filters).filter(
    (v) => v !== "" && v !== false && v !== "createdAt_desc"
  ).length;

  return (
    <div>
      <div className="flex items-center justify-end gap-3 py-1 text-sm">
        <button
          type="button"
          onClick={handleCreateAcademy}
          aria-label={t("academy.addAcademyAria")}
          className={toolbarIconButtonClass}
        >
          <BoldIcon
            name="add-square"
            size={TOOLBAR_ICON_SIZE}
            className="block"
          />
        </button>
        <button
          type="button"
          onClick={() => router.push("/search?type=user")}
          aria-label={t("academy.searchAria")}
          className={toolbarIconButtonClass}
        >
          <BoldIcon
            name="search-normal"
            size={TOOLBAR_ICON_SIZE}
            className="block"
          />
        </button>
        <button
          type="button"
          onClick={() => setShowFilterModal(true)}
          aria-label={t("academy.filterAria")}
          className={toolbarIconButtonClass}
        >
          <BoldIcon name="candle" size={TOOLBAR_ICON_SIZE} className="block" />
        </button>
      </div>

      {showFilterModal && (
        <AcademyFilterModal
          showFilterModal={showFilterModal}
          setShowFilterModal={setShowFilterModal}
          filters={filters}
          setFilters={setFilters}
          categories={categories}
          categoriesLoading={categoriesLoading}
          sortOptions={sortOptions}
          courseTypes={courseTypes}
          onApply={applyFilters}
          onClear={clearFilters}
          activeFiltersCount={activeFiltersCount}
        />
      )}
    </div>
  );
}
