"use client";

import React, { useState } from "react";
import "react-multi-carousel/lib/styles.css";
import Loader from "@/components/ui/Loader";
import { useTranslation } from "react-i18next";
import "moment/locale/ar";
import { Modal } from "@/components/ui/Modal";
import DeleteEventModal from "./DeleteEventModal";
import InfiniteScroll from "react-infinite-scroll-component";
import { type EventCardProps, type EventData } from "./eventListCardTypes";
import { useEventListCard } from "./useEventListCard";
import EventListTile from "./EventListTile";
import QueryErrorNotice from "@/components/shared/QueryErrorNotice";

const EventListCard: React.FC<EventCardProps> = ({
  filters,
  searchQuery = "",
  event_type,
  is_homepage = false,
}) => {
  const { t } = useTranslation();
  const {
    eventLoading,
    eventError,
    eventErrorDetail,
    refetch,
    reload,
    eventData,
    selectedLanguage,
    allEvents,
    hasMore,
    user,
    deleteModalInfo,
    setDeleteModalInfo,
    eventTypeLoading,
    categoryState,
    refetchEventTypes,
    loadMore,
  } = useEventListCard({
    filters,
    searchQuery,
    event_type,
  });

  /* The page number is part of the query key, so every page after the first
     starts with `isLoading` true and no `data`. Treating that as "loading"
     replaced the whole list with the full-screen loader on each scroll, which
     unmounted the cards and threw the reader back to the top. Only the first
     page (nothing accumulated yet) gets the full loader; later pages show
     InfiniteScroll's small spinner under the cards already on screen. */
  const isInitialLoad =
    allEvents.length === 0 && (eventLoading || Boolean(event_type && eventTypeLoading));

  /* The total survives the in-between render where the next page has no
     `data` yet, so the results line does not blink on every load. */
  const liveTotal = eventData?.meta?.pagination?.total;
  const [lastTotal, setLastTotal] = useState<number | undefined>(undefined);
  if (typeof liveTotal === "number" && liveTotal !== lastTotal) {
    setLastTotal(liveTotal);
  }
  const total = typeof liveTotal === "number" ? liveTotal : lastTotal;

  if (categoryState === "error") {
    return <div role="alert" className="py-8 text-center text-secondary-102">
      <p>{t("COMMON.EVENT_CATEGORY_LOAD_FAILED")}</p>
      <button type="button" className="mt-2 underline" onClick={() => void refetchEventTypes()}>{t("COMMON.EVENT_CATEGORY_RETRY")}</button>
    </div>;
  }
  if (categoryState === "unavailable") {
    return <p role="status" className="py-8 text-center text-lg font-medium text-secondary-102">{t("COMMON.EVENT_CATEGORY_UNAVAILABLE")}</p>;
  }

  /* A failed first page is a failure, not "no events" — the two used to read
     the same, so an outage told visitors there was nothing on. */
  if (eventError && allEvents.length === 0) {
    return <QueryErrorNotice error={eventErrorDetail} onRetry={() => { void refetch(); }} />;
  }

  if (isInitialLoad) {
    return <Loader />;
  }

  const hasNoEvents = allEvents.length === 0;

  return (
    <>
      {deleteModalInfo.isOpen && (
        <Modal
          title={t("COMMON.DELETE_EVENT")}
          open={deleteModalInfo.isOpen}
          onClose={() => setDeleteModalInfo({ isOpen: false })}
          size="small"
          position="default"
        >
          <DeleteEventModal
            eventId={deleteModalInfo.eventId!}
            setOpenModal={() => setDeleteModalInfo({ isOpen: false })}
            refetch={reload}
            eventTitle={deleteModalInfo.eventTitle}
          />
        </Modal>
      )}
      {hasNoEvents ? (
        <div className="text-center py-8 text-secondary-102 text-lg font-medium">
          {t("COMMON.NO_EVENTS_AVAILABLE")}
        </div>
      ) : (
        <>
          {/* `meta.pagination.total` is the count across every page, not just the
            ones loaded so far — that's the number to show. */}
          {typeof total === "number" && (
            <p className="pb-4 text-secondary-102 text-base mobilescreen:text-sm">
              {t("COMMON.RESULTS_COUNT", { total })}
            </p>
          )}
          <InfiniteScroll
            dataLength={allEvents.length}
            next={loadMore}
            hasMore={hasMore}
            hasChildren={allEvents.length > 0}
            loader={<Loader inline size="sm" />}
            endMessage={
              <p className="text-center py-4 text-secondary-102">
                {t("COMMON.NO_MORE_EVENTS")}
              </p>
            }
          >
            <div className="listing-card-grid grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 ">
              {allEvents.map((item: EventData) => (
                <EventListTile
                  key={item.id}
                  item={item}
                  user={user}
                  selectedLanguage={selectedLanguage}
                  onRequestDelete={setDeleteModalInfo}
                  is_homepage={is_homepage}
                />
              ))}
            </div>
          </InfiniteScroll>
        </>
      )}
    </>
  );
};

export default EventListCard;
