"use client";

import { useState } from "react";
import { useIsFetching } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import Searchbar from "@/components/ui/Searchbar";
import { Button } from "@/components/ui/Button";
import { TiPlus } from "react-icons/ti";
import ListingHeader from "@/components/shared/ListingHeader";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { Modal } from "@/components/ui/Modal";
import AllEventFilterModal, {
  AllEventsFiltersData,
} from "./AllEventFilterModal";
import { useAuthStore } from "@/store/authStore";
import { canPublish } from "@/lib/publishPermissions";
import PlacementBanner from "@/components/shared/PlacementBanner";
import EventListCard from "./EventListCard";
import { useDebouncedValue } from "@/hooks/useDebouncedValue";

export default function Events() {
  const { t } = useTranslation();
  const searchParams = useSearchParams();
  const [open, setOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");
  const debouncedSearch = useDebouncedValue(searchQuery);
  const fetchingEvents = useIsFetching({ queryKey: ["events-list"] }) > 0;
  const [clearFiltersKey, setClearFiltersKey] = useState(0);
  const [isFilterDirty, setIsFilterDirty] = useState(false);
  const [isFilterEmpty, setIsFilterEmpty] = useState(true);

  const tagsFromUrl = searchParams ? searchParams.get("tags") : null;

  const [filters, setFilters] = useState<AllEventsFiltersData>({
    startDate: "",
    endDate: "",
    tags: tagsFromUrl ? [tagsFromUrl] : [],
    location: "",
    gender: "",
    age: [null, null],
    type: "",
    participation_type: "",
    matchMyInterest: false,
    status: "",
  });

  const user = useAuthStore((s) => s.user);

  /*
   * `filters` is the reader's own state — the filter modal writes it — so the
   * `?tags=` parameter can only *adjust* it, which is why the initialiser above
   * already seeds it. This handles the remaining case: arriving from one tag
   * link at another without unmounting.
   *
   * React's documented adjust-on-change pattern rather than an effect
   * (react.dev/learn/you-might-not-need-an-effect, "Adjusting some state when
   * a prop changes"). React throws away this render and re-runs before
   * committing, so nothing is painted with the stale tag — whereas the effect
   * let one frame render, and one query fire, with the previous tag still in
   * `filters`. The comparison is on the tag string, not the `searchParams`
   * object, which is a fresh instance on some renders.
   */
  const [tagsAppliedFromUrl, setTagsAppliedFromUrl] = useState(tagsFromUrl);
  if (tagsFromUrl !== tagsAppliedFromUrl) {
    setTagsAppliedFromUrl(tagsFromUrl);
    if (tagsFromUrl) {
      setFilters((prev) => ({ ...prev, tags: [tagsFromUrl] }));
    }
  }

  const handleApplyFilters = (newFilters: AllEventsFiltersData) => {
    setFilters(newFilters);
    setOpen(false);
  };

  return (
    <>
      <Modal
        open={open}
        onClose={() => setOpen(false)}
        title={t("COMMON.FILTER")}
        compactFilter
        size="md"
        footer={
          <div className="flex xss:flex-col justify-center w-full gap-5">
            <Button
              variant="primary"
              size="medium"
              className="xss:!w-full"
              onClick={() => {
                const form = document.querySelector("form") as HTMLFormElement;
                if (form) form.requestSubmit();
              }}
              disabled={!isFilterDirty}
            >
              {t("COMMON.APPLY")}
            </Button>
            <Button
              variant="secondary"
              size="medium"
              className="xss:!w-full"
              onClick={() => {
                setFilters({
                  startDate: "",
                  endDate: "",
                  tags: [],
                  location: "",
                  gender: "",
                  age: [null, null],
                  type: "",
                  participation_type: "",
                  matchMyInterest: false,
                  status: "",
                });
                setClearFiltersKey((prev) => prev + 1);
              }}
              disabled={isFilterEmpty}
            >
              {t("COMMON.CLEAR")}
            </Button>
          </div>
        }
      >
        <AllEventFilterModal
          key={clearFiltersKey}
          onApply={handleApplyFilters}
          initialValues={filters}
          onDirtyChange={setIsFilterDirty}
          onEmptyChange={setIsFilterEmpty}
          isInnerModal={false}
        />
      </Modal>

      <div className="border-t border-[#000] opp-itm-shadow">
        <div className="2xl:px-5 px-3 mobilescreen:px-[13px] 2xl:w-[75%] laptopmain:w-[83%] laptop:w-[78%] laptopitm:w-[85%] lg:w-[90%] md:w-[85%] w-[90%] mx-auto py-5 md:py-6 relative">
          <PlacementBanner placement="events" />
          <ListingHeader title={t("COMMON.LATEST.EVENTS")} colorClassName="text-primary-801">
            <div className="w-full sm:w-[300px] lg:w-[340px]">
              <Searchbar
                onSearchChange={setSearchQuery}
                value={searchQuery}
                showClearButton
                isLoading={searchQuery !== debouncedSearch || fetchingEvents}
                onFilterClick={() => setOpen(true)}
              />
            </div>

            {/* Organizations only — not volunteer teams (`lib/publishPermissions.ts`). */}
            {canPublish(user, "events") && (
              <Link
                className="single-line-button !w-full sm:!w-auto !px-5 !h-10 !rounded-full !text-sm font-bold bg-primary-5 text-white flex items-center justify-center gap-2"
                href="/event-form"
              >
                <TiPlus />
                {t("COMMON.CREATE.EVENTS")}
              </Link>
            )}
          </ListingHeader>

          <div className="dotlist-white horizontal_scroll">

            <EventListCard
              event_type=""
              filters={filters}
              searchQuery={debouncedSearch}
              is_homepage={true}
            />
          </div>
        </div>
      </div>
    </>
  );
}
