"use client";
import { useRouter, useSearchParams } from "next/navigation";
import React, { useEffect, useState } from "react";
import toast from "react-hot-toast";
import BoldIcon from "@/components/ui/BoldIcon";
import { getCreateProjectPath } from "@/lib/getCreateContentPath";
import FilterModal from "./FilterModal";

const expertiseList = [
  { name: "مدلینگ", color: "#B89FFF" },
  { name: "زیبایی", color: "#23bace" },
  { name: "عکاسی", color: "#dace63" },
];

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

interface ProjectsFilterProps {
  expertise: string;
}

function ProjectsFilter({ expertise }: ProjectsFilterProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [showFilterModal, setShowFilterModal] = useState<boolean>(false);
  const [filterRequestsPrice, setFilterRequestsPrice] = useState<string>("");
  const [filterAge, setFilterAge] = useState<string>("");
  const [filterGender, setFilterGender] = useState<string>("");
  const [userType, setUserType] = useState<string | null>(null);

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

  const handleCreateProject = () => {
    if (!userType) {
      toast.error("لطفا ابتدا در سایت وارد شوید یا ثبت نام کنید.");
      return;
    }
    router.push(getCreateProjectPath());
  };

  // مقداردهی اولیه از URL
  useEffect(() => {
    setFilterRequestsPrice(
      searchParams.get("most_requests")
        ? "request"
        : searchParams.get("most_price")
        ? "price"
        : ""
    );
    setFilterAge(searchParams.get("age") || "");
    setFilterGender(searchParams.get("gender") || "");
  }, [searchParams]);

  const handleFilterChange = (filter?: string) => {
    const currentQuery = new URLSearchParams(window.location.search);

    if (filter) {
      currentQuery.set("expertise", filter);
    }

    // فقط یکی از `most_requests` یا `most_price` در URL بماند
    currentQuery.delete("most_requests");
    currentQuery.delete("most_price");

    if (filterRequestsPrice) {
      currentQuery.set(
        filterRequestsPrice === "request" ? "most_requests" : "most_price",
        "true"
      );
    }

    if (filterAge) currentQuery.set("age", filterAge);
    if (filterGender) currentQuery.set("gender", filterGender);

    router.push(`/projects?${currentQuery.toString()}`);
  };

  const clearFilters = () => {
    setFilterRequestsPrice("");
    setFilterAge("");
    setFilterGender("");

    const currentQuery = new URLSearchParams(window.location.search);
    currentQuery.delete("most_requests");
    currentQuery.delete("most_price");
    currentQuery.delete("age");
    currentQuery.delete("gender");

    router.push(`/projects?${currentQuery.toString()}`);
  };

  return (
    <div>
      <div className="flex items-center justify-between relative px-4 text-sm">
        <div className="flex items-center gap-3">
          {expertiseList.map((item) => (
            <button
              key={item.name}
              className="border rounded-full px-4 py-1"
              onClick={() => handleFilterChange(item.name)}
              style={{
                borderColor: item.color,
                backgroundColor: expertise === item.name ? item.color : "",
              }}
            >
              {item.name}
            </button>
          ))}
        </div>
        <div className="flex items-center gap-3 shrink-0 self-center">
          <button
            type="button"
            onClick={handleCreateProject}
            aria-label="ثبت پروژه"
            className={toolbarIconButtonClass}
          >
            <BoldIcon name="add-square" size={TOOLBAR_ICON_SIZE} className="block" />
          </button>
          <button
            type="button"
            onClick={() => router.push("/search")}
            aria-label="جستجو"
            className={toolbarIconButtonClass}
          >
            <BoldIcon name="search-normal" size={TOOLBAR_ICON_SIZE} className="block" />
          </button>
          <button
            type="button"
            onClick={() => setShowFilterModal(true)}
            aria-label="فیلتر"
            className={toolbarIconButtonClass}
          >
            <BoldIcon name="candle" size={TOOLBAR_ICON_SIZE} className="block" />
          </button>
        </div>
      </div>
      {showFilterModal && (
        <FilterModal
          setShowFilterModal={setShowFilterModal}
          showFilterModal={showFilterModal}
          setFilterRequestsPrice={setFilterRequestsPrice}
          setFilterAge={setFilterAge}
          setFilterGender={setFilterGender}
          filterRequestsPrice={filterRequestsPrice}
          filterAge={filterAge}
          filterGender={filterGender}
          handleFilterChange={handleFilterChange}
          clearFilters={clearFilters}
        />
      )}
    </div>
  );
}

export default ProjectsFilter;
