"use client";

import { useState } from "react";
import { useTranslation } from "react-i18next";
import Searchbar from "@/components/ui/Searchbar";
import { Button } from "@/components/ui/Button";
import { TiPlus } from "react-icons/ti";
import { VolunteerCard, SponsorsClient } from "@/features/home";
import ListingHeader from "@/components/shared/ListingHeader";
import OpportunityTypeModal from "./OpportunityTypeModal";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useIsFetching } from "@tanstack/react-query";
import { useAuthStore } from "@/store/authStore";
import { canPublish } from "@/lib/publishPermissions";
import PlacementBanner from "@/components/shared/PlacementBanner";
import OpportunityFilterDialog from "./OpportunityFilterDialog";
import { useOpportunityFilters } from "./useOpportunityFilters";
import { type AllOpportunitiesFiltersData } from "./opportunityFilters";
import { useDebouncedValue } from "@/hooks/useDebouncedValue";

export default function Opportunities() {
  const { t } = useTranslation();
  const [opportunityModalOpen, setOpportunityModalOpen] = useState(false);
  const router = useRouter();

  const [open, setOpen] = useState(false);
  const user = useAuthStore((s) => s.user);

  const [searchQuery, setSearchQuery] = useState("");
  const debouncedSearch = useDebouncedValue(searchQuery);
  const filterState = useOpportunityFilters();

  /*
   * Two full list queries used to sit here — `opportunities-check` and
   * `learnserve-check` — built from these same filters and then never read.
   * `VolunteerCard` fetches both lists itself under its own keys, which is
   * what the spinner below watches, so every filter or keystroke fired two
   * extra round-trips whose responses were dropped on the floor. An effect
   * below re-fired them on each change, doubling that again.
   */
  /**
   * The two lists are fetched inside `VolunteerCard`, so the search bar watches
   * those query keys directly rather than the counts fetched above. Result: a
   * small spinner in the field while a search/filter is in flight, instead of
   * the full-screen loader that used to swallow the page.
   */
  const isSearching =
    useIsFetching({ queryKey: ["volunteer-opportunities"] }) +
      useIsFetching({ queryKey: ["learn-serve-opportunities"] }) >
    0;

  // `lib/publishPermissions.ts`: a trainer may only publish development
  // opportunities, so the type picker is skipped when there is one choice.
  const canPublishVolunteer = canPublish(user, "volunteer");
  const canPublishLearnServe = canPublish(user, ["development", "internship"]);
  const handleCreateClick = () => {
    if (canPublishVolunteer && canPublishLearnServe) {
      setOpportunityModalOpen(true);
      return;
    }
    router.push(
      canPublishVolunteer ? "/volunteer-form" : "/learn-and-share-form",
    );
  };

  const handleOpportunityTypeSelect = (type: "volunteer" | "learn-serve") => {
    setOpportunityModalOpen(false);
    if (type === "volunteer") {
      router.push("/volunteer-form");
    } else if (type === "learn-serve") {
      router.push("/learn-and-share-form");
    }
  };

  const handleApplyFilters = (newFilters: AllOpportunitiesFiltersData) => {
    filterState.setFilters(newFilters);
    setOpen(false);
  };

  return (
    <>
      <OpportunityFilterDialog
        open={open}
        onClose={() => setOpen(false)}
        filters={filterState.filters}
        onApply={handleApplyFilters}
        onClear={filterState.clearFilters}
        clearFiltersKey={filterState.clearFiltersKey}
        isFilterDirty={filterState.isFilterDirty}
        onDirtyChange={filterState.setIsFilterDirty}
        isFilterEmpty={filterState.isFilterEmpty}
        onEmptyChange={filterState.setIsFilterEmpty}
        showLearnServeFields
        showVolunteerFields
      />

      <OpportunityTypeModal
        open={opportunityModalOpen}
        onClose={() => setOpportunityModalOpen(false)}
        onSelect={handleOpportunityTypeSelect}
      />

      <div className="border-t border-[#000] opp-itm opp-itm-shadow">
        <div className="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">
          <div className="2xl:px-5 px-3 mobilescreen:px-[13px]">
            <PlacementBanner placement="opportunities" />
          </div>
          <div className="2xl:px-5 px-3 mobilescreen:px-[13px]">
          <ListingHeader title={t("COMMON.OPPORTUNITIES")} colorClassName="text-primary-5">
            <div className="w-full sm:w-[300px] lg:w-[340px]">
              <Searchbar
                value={searchQuery}
                onFilterClick={() => setOpen(true)}
                onSearchChange={(value) => setSearchQuery(value)}
                isLoading={isSearching}
              />
            </div>
            {(canPublishVolunteer || canPublishLearnServe) && (
              <Button
                variant="primary"
                onClick={handleCreateClick}
                className="!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"
                type="button"
              >
                <TiPlus />
                {t("COMMON.CREATE.AN.OPPORTUNITIES")}
              </Button>
            )}
          </ListingHeader>
          </div>

          <div className="dotlist-white">

            <div className="2xl:px-5 px-3 mobilescreen:px-[13px] flex justify-between items-center">
              <h2 className="text-xl md:text-2xl text-primary-802 font-bold leading-none">
                {t("COMMON.VOLUNTEER")}
              </h2>
              {/* {hasOpportunityData && ( */}
              <Link
                href="/volunteer-opportunities-list"
                className="text-primary-802 font-bold text-base"
              >
                {t("COMMON.SHOW.ALL")}
              </Link>
              {/* )} */}
            </div>

            <VolunteerCard
              buttonText={undefined}
              isOpportunity
              currentUser={user}
              filters={filterState.filters}
              searchQuery={debouncedSearch}
              is_homepage={true}
            />
          </div>
        </div>
      </div>

      <div className="py-[40px] bg-[#F0F0F0] opp-itm-shadow">
        <div className="2xl:w-[75%] laptopmain:w-[83%] laptop:w-[78%] laptopitm:w-[85%] lg:w-[90%] md:w-[85%] w-[90%] mx-auto relative dotlist-white">
          <div className="2xl:px-5 px-3 mobilescreen:px-[13px] flex justify-between items-center">
            <h2 className="text-xl md:text-2xl text-primary-803 font-bold">
              {t("COMMON.LEARN.SERVE")}
            </h2>
            {/* {hasLearnServeData && ( */}
            <Link
              href="/development-opportunities-list"
              className="text-primary-803 font-bold text-base"
            >
              {t("COMMON.SHOW.ALL")}
            </Link>
            {/* )} */}
          </div>

          <VolunteerCard
            buttonText={undefined}
            isLearnServe
            currentUser={user}
            filters={filterState.filters}
            searchQuery={debouncedSearch}
            is_homepage={true}
          />
        </div>
      </div>

      <div className="2xl:pt-[70px] laptopmain:pt-[40px] lg:pt-[40px] md:pt-[40px] pt-[40px]">
        <SponsorsClient />
      </div>
    </>
  );
}
