"use client";

import { useState } from "react";
import Image from "next/image";
import { useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { FaDownload, FaGraduationCap, FaHandHoldingHeart } from "react-icons/fa6";

import CertificatePreviewModal from "./CertificatePreviewModal";
import Loader from "@/components/ui/Loader";
import QueryErrorNotice from "@/components/shared/QueryErrorNotice";
import {
  downloadUserCertificate,
  getUserCertificates,
} from "@/features/profile/services/profileApi";
import type { ProfileCertificate as SharedProfileCertificate } from "../ProfileCertificateTabs";
import { useLanguageStore } from "@/store/languageStore";
import { certificateKindLabelKey } from "./individualProfile";

/* The shared narrowing — see `ProfileCertificateTabs`, which documents why it
   is derived from the endpoint's record rather than re-declared. */
type ProfileCertificate = SharedProfileCertificate;

type Chip = "all" | "volunteer" | "development";

const isHtml = (url: string) => /\.html?(?:$|[?#])/i.test(url);

const kindOf = (certificate: ProfileCertificate) =>
  certificate.certificate_kind ??
  (certificate.registration_type === "volunteer" ? "volunteering" : "course");

/**
 * Your own certificates only: `/user-certificates/` always answers for the
 * caller (BE-46), so the tab is not offered on someone else's profile.
 *
 * The list is unpaginated, so it is fetched once and the three chips — and
 * their counts — are worked out here from `registration_type`.
 */
export default function ProfileCertificatesTab({ userId }: { userId: string }) {
  const { t } = useTranslation();
  const language = useLanguageStore((s) => s.language);
  const [preview, setPreview] = useState<ProfileCertificate | null>(null);
  const [chip, setChip] = useState<Chip>("all");
  const [downloadingId, setDownloadingId] = useState<number | null>(null);

  const { data, isLoading, isError, error, refetch } = useQuery({
    queryKey: ["user-certificates", userId, "all"],
    queryFn: () => getUserCertificates(userId),
    enabled: Boolean(userId),
  });

  if (isLoading) return <Loader inline className="py-16" />;
  // A failed load is not "no certificates".
  if (isError) return <QueryErrorNotice error={error} onRetry={() => { void refetch(); }} />;

  /* `certificate_image` is nullable on the payload — `getimg()` answers null
     when a certified row has no stored file — and every renderer below treats
     it as a URL. Filtered rather than rendered, so a null never reaches an
     `href` or an `<img src>`. */
  const all: ProfileCertificate[] = (
    Array.isArray(data?.data) ? data.data : []
  ).filter((item): item is ProfileCertificate => Boolean(item.certificate_image));
  const volunteer = all.filter((item) => item.registration_type === "volunteer");
  const development = all.filter((item) => item.registration_type !== "volunteer");
  const lists: Record<Chip, ProfileCertificate[]> = { all, volunteer, development };
  const shown = lists[chip];

  const chips: Array<[Chip, string]> = [
    ["all", "COMMON.ALL"],
    ["volunteer", "COMMON.VOLUNTEER"],
    ["development", "COMMON.PROFILE_DEVELOPMENT"],
  ];

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

  return (
    <div>
      {preview && <CertificatePreviewModal
        src={preview.certificate_image}
        title={(language === "ar" ? preview.opportunity__title_ar : preview.opportunity__title_en) || preview.opportunity__title_en || preview.opportunity__title_ar || ""}
        onClose={() => setPreview(null)}
        onDownload={() => { void download(preview); }}
        downloading={downloadingId === preview.registration_id}
      />}
      <div className="flex flex-wrap gap-2">
        {chips.map(([value, labelKey]) => {
          const active = value === chip;
          return (
            <button
              key={value}
              type="button"
              onClick={() => setChip(value)}
              className={`flex items-center gap-2 rounded-full px-4 py-1.5 text-sm font-semibold ${
                active ? "bg-primary-5 text-white" : "bg-[#29246D0F] text-primary-5"
              }`}
            >
              {t(labelKey)}
              <span className={`rounded-full px-2 text-xs ${active ? "bg-white text-primary-5" : "bg-white/70"}`}>
                {lists[value].length}
              </span>
            </button>
          );
        })}
      </div>

      {shown.length === 0 ? (
        <p className="py-10 text-center text-secondary-102">{t("COMMON.NO_CERTIFICATES_FOUND")}</p>
      ) : (
        <div className="mt-5 listing-card-grid grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3">
          {shown.map((certificate) => {
            const kind = kindOf(certificate);
            const isVolunteering = kind === "volunteering";
            const title =
              (language === "ar" ? certificate.opportunity__title_ar : certificate.opportunity__title_en) ||
              certificate.opportunity__title_en ||
              certificate.opportunity__title_ar ||
              "";
            return (
              <article
                key={`${certificate.registration_type}-${certificate.registration_id}`}
                className="relative flex overflow-hidden rounded-2xl border border-[#29246D1A] bg-white shadow-sm transition-shadow hover:shadow-md"
              >
                <button type="button" onClick={() => setPreview(certificate)}
                  aria-label={`${t("COMMON.CERTIFICATE_PREVIEW")}: ${title}`}
                  className="absolute inset-0 z-10 cursor-zoom-in rounded-2xl focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-[-3px] focus-visible:outline-primary-5" />
                <div className="relative aspect-[1.414/1] flex-1 bg-[#3E397B]">
                  {isHtml(certificate.certificate_image) ? (
                    <iframe
                      src={certificate.certificate_image}
                      title={title}
                      tabIndex={-1}
                      className="pointer-events-none h-full w-full border-0"
                    />
                  ) : (
                    <Image
                      src={certificate.certificate_image}
                      alt={title}
                      fill
                      unoptimized
                      className="object-cover"
                    />
                  )}
                  <button
                    type="button"
                    onClick={() => download(certificate)}
                    disabled={downloadingId === certificate.registration_id}
                    aria-label={t("COMMON.DOWNLOAD")}
                    className="absolute bottom-2 start-2 z-20 flex h-8 w-8 items-center justify-center rounded-full bg-white/90 text-primary-5 disabled:opacity-50"
                  >
                    <FaDownload size={13} aria-hidden />
                  </button>
                </div>
                {/* The vertical side label from the design: what it was earned for. */}
                <div
                  className={`flex w-10 flex-col items-center justify-center gap-2 text-white ${
                    isVolunteering ? "bg-[#5B6CF0]" : "bg-[#6FB3C0]"
                  }`}
                >
                  {isVolunteering ? <FaHandHoldingHeart size={14} aria-hidden /> : <FaGraduationCap size={14} aria-hidden />}
                  <span className="text-xs font-bold tracking-widest [writing-mode:vertical-rl]">
                    {t(certificateKindLabelKey(kind))}
                  </span>
                </div>
              </article>
            );
          })}
        </div>
      )}
    </div>
  );
}
