"use client";
import { canEditOrDelete } from "@/features/shared/opportunityButtonState";

import React from "react";
import moment from "moment";
import { useClock } from "@/hooks/useClock";
import Image from "next/image";
import { useTranslation } from "react-i18next";
import InfiniteScroll from "react-infinite-scroll-component";

import Loader from "@/components/ui/Loader";
import OpportunityCard from "@/features/opportunities/components/OpportunityCard";
import { type ProfileVolunteerCardProps } from "./profileVolunteerCardTypes";
import { useProfileVolunteerCard } from "./useProfileVolunteerCard";
import ProfileDeleteOpportunityModal from "./ProfileDeleteOpportunityModal";
import IconButton from "@/components/ui/IconButton";
import QueryErrorNotice from "@/components/shared/QueryErrorNotice";

const ProfileVolunteerCard: React.FC<ProfileVolunteerCardProps> = ({
  buttonText,
  filter_type,
  filters,
  searchQuery = "",
  currentUser,
  isPublicProfile = false,
  user_id,
  type,
  useNewApi = false, // Default to false (use old API)
  profileBadges,
  apiFilterType,
}) => {
  // Language is read inside OpportunityCard now — this component no longer
  // renders any localized field itself.
  const { t } = useTranslation();
  const clock = useClock(1000);
  const {
    opportunities,
    deleteModalInfo,
    setDeleteModalInfo,
    hasMore,
    isLoading,
    isFetching,
    isError,
    error,
    refetch,
    loadMore,
    isVolunteerOpportunity,
    getStatusStyles,
    getBgClassByType,
    getBorderClassByType,
    getDeleteIconByType,
    getPersonIconByType,
    detailHref,
    hasNoOpportunities,
  } = useProfileVolunteerCard({
    filter_type,
    filters,
    searchQuery,
    currentUser,
    isPublicProfile,
    user_id,
    type,
    useNewApi,
    apiFilterType,
    buttonText,
  });

  return (
    <div>
      <ProfileDeleteOpportunityModal
        deleteModalInfo={deleteModalInfo}
        setDeleteModalInfo={setDeleteModalInfo}
        opportunities={opportunities}
        refetch={refetch}
      />

      {isError ? <QueryErrorNotice error={error} onRetry={() => { void refetch(); }} /> : hasNoOpportunities && !isLoading && !isFetching ? (
        <div className="text-center py-8 text-secondary-102 text-lg font-medium">
          {t("COMMON.NO_VOLUNTEER_OPPORTUNITIES_AVAILABLE")}
        </div>
      ) : (
        <InfiniteScroll
          dataLength={opportunities.length}
          next={loadMore}
          hasMore={hasMore}
          hasChildren={opportunities.length > 0}
          loader={<Loader inline />}
          endMessage={
            opportunities.length > 0 ? (
              <p className="text-center py-4 text-secondary-102">
                {t("COMMON.NO_MORE_OPPORTUNITIES")}
              </p>
            ) : null
          }
          className="overflow-hidden pt-[25px] 2xl:pt-[50px] laptop:pt-[40px] lg:pt-[24px] md:pt-[30px] cross-class-visible"
        >
          <div className="listing-card-grid grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 ">
            {opportunities.map((item) => {
              return (
                // Volunteer and learn-serve opportunities are separate
                // backend models with their own id sequences, so a plain
                // `item.id` can collide between the two once both types are
                // combined in one list (no type filter applied).
                <div
                  key={`${item.opportunity_type}-${item.id}`}
                  className="min-w-0"
                >
                  <OpportunityCard
                    item={item}
                    isLearnServe={
                      !isVolunteerOpportunity(item.opportunity_type)
                    }
                    detailHref={detailHref(item)}
                    borderClass={getBorderClassByType(item.opportunity_type)}
                    buttonClass={getBgClassByType(item.opportunity_type)}
                    peopleIconSrc={getPersonIconByType(item.opportunity_type)}
                    /* The profile's paid/free, provider/participant and
                       attended/absent pills now sit on the cover, in the
                       profile owner's terms (`cardStatusBadges`). */
                    badgePerspective={
                      profileBadges === "organizer"
                        ? "profile-organizer"
                        : profileBadges === "sponsor"
                          ? "profile-sponsor"
                          : profileBadges === "individual"
                          ? isPublicProfile
                            ? "profile-individual-public"
                            : "profile-individual"
                          : "viewer"
                    }
                    statusPill={
                      profileBadges ? null : // The "organized" tab already groups by status, so the
                      // pill would just repeat the tab label there.
                      !(useNewApi && filter_type === "organized") &&
                        item.opportunity_status ? (
                        <span
                          className={`shrink-0 whitespace-nowrap rounded-full px-4 py-1 text-sm font-medium ${getStatusStyles(
                            item.opportunity_status,
                            item.opportunity_type,
                          )}`}
                        >
                          {item.opportunity_status === "inprogress"
                            ? t("COMMON.IN_PROGRESS")
                            : item.opportunity_status === "completed"
                              ? t("COMMON.FINISHED")
                              : t("COMMON.UPCOMING")}
                        </span>
                      ) : null
                    }
                    headerOverlay={
                      currentUser &&
                      item.created_by?.id === currentUser.id &&
                      item.opportunity_status !== "completed" &&
                      item.opportunity_status !== "inprogress" &&
                      Boolean(clock) && canEditOrDelete(item, moment(clock)) &&
                      (item as { can_delete?: boolean }).can_delete !== false &&
                      (item as { has_successful_payments?: boolean }).has_successful_payments !== true &&
                      (item as { has_active_payments?: boolean }).has_active_payments !== true ? (
                        <div className="absolute -left-3 -top-3 z-10">
                          {/* A destructive control, so a real button: `<Image onClick>` was
                              unreachable by keyboard and announced as a graphic.
                              The icon's `alt` is emptied because the accessible
                              name now belongs to the button. `stopPropagation`
                              keeps the card's own link from firing. */}
                          <IconButton
                            label={t("COMMON.DELETE")}
                            stopPropagation
                            className="cursor-pointer"
                            onClick={() =>
                              setDeleteModalInfo({
                                isOpen: true,
                                opportunityId: String(item.id),
                                opportunityTitle: {
                                  title_en: item.title_en,
                                  title_ar: item.title_ar,
                                },
                              })
                            }
                          >
                            <Image
                              src={getDeleteIconByType(item.opportunity_type)}
                              alt=""
                              width={27}
                              height={27}
                              className="w-[27px] h-[27px]"
                            />
                          </IconButton>
                        </div>
                      ) : null
                    }
                  />
                </div>
              );
            })}
          </div>
        </InfiniteScroll>
      )}
    </div>
  );
};

export default ProfileVolunteerCard;
