"use client";

import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { toast } from "sonner";
import { downloadUserCertificate, getUserCertificates } from "@/features/profile/services/profileApi";
import { getDropdownChoices } from "@/features/shared/services/dropdowns";
import { useTranslation } from "react-i18next";
import { useAuthStore } from "@/store/authStore";
import { EMPTY_PROFILE_CERTIFICATES, type ProfileCertificate } from "./ProfileCertificateTabs";
import { useLanguageStore } from "@/store/languageStore";
import { ALL_CERTIFICATE_TYPES, CERTIFICATE_FILTER_CHOICE_TYPE, type ChoiceOption } from "./ProfileDescriptionTabs";
import { toastApiError } from "@/lib/api/toastApiError";

/**
 * A volunteer's certificates, paged and filterable by type.
 *
 * Downloading one is not a plain link: HTML certificates are opened in a tab
 * while PDFs are fetched as a blob, because the browser would render the HTML
 * inline and "download" a PDF nobody asked to save.
 */
export function useProfileCertificates(user_id?: string) {
  const { t } = useTranslation();
  const selectedLanguage = useLanguageStore((s) => s.language);
  const user = useAuthStore((s) => s.user);
  const userId = user_id || user?.id?.toString();
  const pageSizeRef = useRef(9);
  const [displayedCount, setDisplayedCount] = useState(9);
  const [downloadingId, setDownloadingId] = useState<number | null>(null);
  const [typeFilter, setTypeFilter] = useState("all");

  // The chip is a query param, so the server owns the filtering and the list
  // that gets paged on screen is the list the server returned.
  const { data: response, isLoading } = useQuery({
    queryKey: ["user-certificates", userId, typeFilter],
    queryFn: () =>
      getUserCertificates(
        userId as string,
        typeFilter === ALL_CERTIFICATE_TYPES ? undefined : typeFilter
      ),
    enabled: Boolean(userId),
  });

  // The filter's own options are backend-managed master choices.
  const { data: typeChoices } = useQuery({
    queryKey: ["dropdown", CERTIFICATE_FILTER_CHOICE_TYPE],
    queryFn: () => getDropdownChoices(CERTIFICATE_FILTER_CHOICE_TYPE),
    retry: false,
  });

  const typeTabs = useMemo(() => {
    const choices: ChoiceOption[] = Array.isArray(typeChoices?.data)
      ? typeChoices.data
      : [];

    return [
      { value: "all", label: t("COMMON.ALL") },
      ...choices
        .filter((choice) => choice.value_en)
        .map((choice) => ({
          // The English value is the match key — it is what the certificate's
          // own learning type is reported as, and it does not change with the
          // viewer's language the way the label does.
          value: String(choice.value_en),
          label:
            (selectedLanguage === "ar" ? choice.value_ar : choice.value_en) ||
            String(choice.value_en),
        })),
    ];
  }, [typeChoices, selectedLanguage, t]);

  // Already filtered by the API — there is deliberately no second filter here.
  // Duplicating the rule client-side is how the two drift apart, and it would
  // also mean paging a list the server never returned.
  /* The `certificate_image` filter is the one narrowing done here: the payload
     types it nullable (`getimg()` answers null for a certified row whose file
     is missing) while the grid treats it as a URL. */
  const allCertificates: ProfileCertificate[] = Array.isArray(response?.data)
    ? response.data.filter((item): item is ProfileCertificate =>
        Boolean(item.certificate_image)
      )
    : EMPTY_PROFILE_CERTIFICATES;

  const certificates = allCertificates.slice(0, displayedCount);
  const hasMore = displayedCount < allCertificates.length;

  // Reset paging here rather than in an effect on `typeFilter`: the count only
  // ever needs resetting because the user changed the chip.
  const handleTypeFilterChange = (value: string) => {
    setTypeFilter(value);
    setDisplayedCount(pageSizeRef.current);
  };

  const updatePageSize = useCallback(() => {
    const width = window.innerWidth;
    const nextPageSize = width >= 1200 ? 9 : width >= 768 ? 8 : 9;
    if (pageSizeRef.current !== nextPageSize) {
      pageSizeRef.current = nextPageSize;
      setDisplayedCount(nextPageSize);
    }
  }, []);

  useEffect(() => {
    const animationFrame = window.requestAnimationFrame(updatePageSize);
    window.addEventListener("resize", updatePageSize);
    return () => {
      window.cancelAnimationFrame(animationFrame);
      window.removeEventListener("resize", updatePageSize);
    };
  }, [updatePageSize]);

  const loadMore = useCallback(() => {
    setDisplayedCount((current) =>
      Math.min(current + pageSizeRef.current, allCertificates.length)
    );
  }, [allCertificates.length]);

  const handleDownloadCertificate = async (
    certificate: ProfileCertificate,
    index: number
  ) => {
    try {
      setDownloadingId(certificate.registration_id);
      const { blob, filename } = await downloadUserCertificate({
        registration_id: certificate.registration_id,
        registration_type: certificate.registration_type,
        fallbackName: `certificate_${index}`,
      });
      const blobUrl = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = blobUrl;
      link.download = filename;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(blobUrl);
      toast.success(t("COMMON.TOAST.DOWNLOAD_IMAGE_SUCCESS"));
    } catch (error) {
      console.error("Certificate download error:", error);
      toast.error(t("COMMON.TOAST.DOWNLOAD_IMAGE_FAILED"));
    } finally {
      setDownloadingId(null);
    }
  };

  const handleShareToLinkedIn = (imageUrl: string) => {
    try {
      const linkedInShareUrl =
        "https://www.linkedin.com/sharing/share-offsite/?url=" +
        encodeURIComponent(imageUrl);
      window.open(linkedInShareUrl, "_blank", "noopener,noreferrer");
    } catch (error) {
      console.error("Error sharing certificate to LinkedIn:", error);
      toastApiError(error, selectedLanguage, t("COMMON.TOAST.SHARE_FAILED"));
    }
  };

  return {
    t,
    isLoading,
    selectedLanguage,
    user,
    userId,
    pageSizeRef,
    displayedCount,
    downloadingId,
    typeFilter,
    typeTabs,
    allCertificates,
    certificates,
    hasMore,
    handleTypeFilterChange,
    updatePageSize,
    loadMore,
    handleDownloadCertificate,
    handleShareToLinkedIn,
  };
}
