"use client";

import Image from "next/image";
import { useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { FaFilePdf } from "react-icons/fa6";

import { getOrganizerProfile } from "@/features/profile/services/profileApi";
import { useAuthStore } from "@/store/authStore";

/**
 * The organizer's two licences, owner-only (client, 2026-10-15):
 *
 * 1. **Company licence** — the documents the organization uploaded when it
 *    signed up (`documents[]`, `EntitiesRegistrationForm`). The details
 *    payload does not carry them, so they are read from the owner's own
 *    `GET /organization-profile/` — the same React Query key the profile
 *    screens use, so it is usually cached already.
 * 2. **Opportunity licence** — this opportunity's `license_image`
 *    (`VolunteerAttachmentSections`). The API sends it only to its owner or an
 *    admin (`ResolvesOpportunitySerializerFields::adminLicenseImageUrl`).
 *
 * A volunteer — anyone but the owner — sees neither. `isOwner` comes from
 * `deriveVolunteerEventView` (`view.isCreator`) rather than a second check
 * here that could disagree with the action bar beside it.
 *
 * An individual trainer publishes without a company, so only an organization
 * account asks for the profile.
 */
export default function LicenseCard({
  image,
  isOwner,
}: {
  image?: string | null;
  isOwner: boolean;
}) {
  const { t } = useTranslation();
  const isOrganization =
    useAuthStore((s) => s.user?.user_type) === "organization";

  const { data: organizerProfile } = useQuery({
    queryKey: ["organizer-profile"],
    queryFn: getOrganizerProfile,
    enabled: isOwner && isOrganization,
    retry: false,
  });
  const companyDocuments = (organizerProfile?.data?.documents ?? []).filter(
    (doc): doc is typeof doc & { document: string } => Boolean(doc.document)
  );

  if (!isOwner || (!image && companyDocuments.length === 0)) return null;

  return (
    <div className="w-full flex flex-col gap-5 relative bg-[#E5E5E5] md:bottom-[50px] bottom-[50px] lg:bottom-[100px] px-[20px] pb-[30px] pt-[20px]">
      {companyDocuments.length > 0 && (
        <LicenseGroup title={t("COMMON.COMPANY_LICENSE")}>
          {companyDocuments.map((doc) => (
            <LicenseFile key={doc.id} url={doc.document} label={t("COMMON.COMPANY_LICENSE")} />
          ))}
        </LicenseGroup>
      )}
      {image && (
        <LicenseGroup title={t("COMMON.OPPORTUNITY_LICENSE")}>
          <LicenseFile url={image} label={t("COMMON.OPPORTUNITY_LICENSE")} />
        </LicenseGroup>
      )}
    </div>
  );
}

function LicenseGroup({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <section className="flex flex-col items-center">
      <p className="text-primary-5 2xl:text-base lg:text-sm text-sm font-bold mb-3">
        {title}
      </p>
      <div className="flex flex-wrap justify-center gap-3">{children}</div>
    </section>
  );
}

/** An image is previewed; a PDF (allowed for company documents) is a link. */
function LicenseFile({ url, label }: { url: string; label: string }) {
  const isPdf = /\.pdf($|\?)/i.test(url);
  return (
    <a href={url} target="_blank" rel="noopener noreferrer" title={label}>
      {isPdf ? (
        <span className="flex h-[120px] w-[160px] flex-col items-center justify-center gap-2 rounded-lg border border-gray-300 bg-white text-primary-5 shadow hover:opacity-90">
          <FaFilePdf className="h-8 w-8" aria-hidden />
          <span className="text-xs font-semibold">PDF</span>
        </span>
      ) : (
        <Image
          src={url}
          alt={label}
          width={400}
          height={200}
          className="max-w-full max-h-[200px] w-auto h-auto object-contain rounded-lg border border-gray-300 shadow hover:opacity-90 transition-opacity cursor-pointer"
          unoptimized
        />
      )}
    </a>
  );
}
