import { Download, LoaderCircle } from "lucide-react";
import { Link } from "react-router-dom";
import type { Resource } from "../api";
import { assetUrl } from "../api";
import { useI18n } from "../i18n";
import { useMemo, useState } from "react";
import { cleanCategoryDisplayName } from "../utils/categoryDisplay";
import { formatDateYmd } from "../utils/format";
import { officialRecommendationCoverFallbacks } from "./FigmaBanner";
import {
  downloadAttachment,
  downloadFile,
} from "./messageStream/utils/downloadFile";

function isPlaceholderAsset(path: string | undefined | null) {
  return !path || path.includes("placeholder-cover");
}

const CARD_CLASS =
  "group flex w-[208px] shrink-0 flex-col overflow-hidden rounded-xl border border-transparent bg-[#1D1E23] transition hover:border-ark-gold/55 md:w-[240px] md:border-ark-line md:bg-ark-panel lg:w-[246.4px] min-[1100px]:max-xl:w-[273px] xl:w-[246.4px]";

type RecommendedResource = Resource & {
  downloadPostId?: string;
  downloadAttachmentId?: string;
};

export function RecommendedCard({
  r,
  visualIndex = 0,
  useFigmaDesign = false,
}: {
  r: RecommendedResource;
  visualIndex?: number;
  useFigmaDesign?: boolean;
}) {
  const { t } = useI18n();
  const [isDownloading, setIsDownloading] = useState(false);
  const figmaCover =
    officialRecommendationCoverFallbacks[
      visualIndex % officialRecommendationCoverFallbacks.length
    ];
  const cover = useMemo(() => {
    if (useFigmaDesign) return figmaCover;
    const original = r.coverImage || r.previewUrl;
    if (isPlaceholderAsset(original)) {
      return figmaCover;
    }
    return assetUrl(original);
  }, [figmaCover, r.coverImage, r.previewUrl, useFigmaDesign]);
  const displayTitle = r.title;
  const displayCategoryName = cleanCategoryDisplayName(r.categoryName);
  const dateStr = formatDateYmd(r.updatedAt);
  const dateTime = r.updatedAt;

  const dl =
    r.isDownloadable && (r.fileUrl || r.previewUrl)
      ? assetUrl(r.fileUrl || r.previewUrl)
      : "";

  return (
    <article className={CARD_CLASS}>
      <Link
        to={`/resource/${r.id}`}
        className="relative block h-[108px] overflow-hidden bg-black md:aspect-[246.4/138.6] md:h-auto"
      >
        {cover ? (
          <img
            src={cover}
            alt=""
            className={`h-full w-full object-cover transition duration-300 ${
              useFigmaDesign
                ? "origin-top scale-[1.08] group-hover:scale-[1.1]"
                : "group-hover:scale-[1.02]"
            }`}
            loading="lazy"
          />
        ) : (
          <div className="h-full w-full bg-gradient-to-br from-neutral-900 to-neutral-950" />
        )}
        {r.badgeLabel ? (
          <span className="absolute left-3 top-3 rounded-md bg-ark-gold px-2.5 py-1 text-xs font-semibold text-black">
            {r.badgeLabel}
          </span>
        ) : null}
      </Link>
      <div className="flex min-h-[131px] flex-1 flex-col p-4 pt-3 md:min-h-[121px]">
        <Link
          to={`/resource/${r.id}`}
          className="text-[15px] font-semibold leading-[21.72px] text-white line-clamp-2 hover:text-ark-gold2 md:text-base md:font-bold md:leading-snug"
        >
          {displayTitle}
        </Link>
        <div className="mt-auto flex items-center justify-between gap-2 pt-4 text-[12px] leading-[17.38px] text-ark-muted">
          <div className="min-w-0 truncate">
            <span className="text-neutral-400">{displayCategoryName}</span>
            <span className="mx-1.5 text-ark-line">·</span>
            <time dateTime={dateTime}>{dateStr}</time>
          </div>
          {dl ? (
            <button
              type="button"
              className="shrink-0 rounded-lg p-1 text-ark-gold outline-none hover:bg-ark-gold/10 focus-visible:ring-2 focus-visible:ring-ark-gold/80 disabled:cursor-wait"
              title={isDownloading ? t("downloading") : t("download")}
              aria-label={isDownloading ? t("downloading") : t("download")}
              aria-busy={isDownloading}
              disabled={isDownloading}
              onClick={async (e) => {
                e.preventDefault();
                e.stopPropagation();
                if (isDownloading) return;
                setIsDownloading(true);
                try {
                  if (r.downloadPostId && r.downloadAttachmentId) {
                    await downloadAttachment(
                      r.downloadPostId,
                      r.downloadAttachmentId,
                      displayTitle,
                    );
                    return;
                  }
                  await downloadFile(dl, displayTitle);
                } catch {
                  /* ignore */
                } finally {
                  setIsDownloading(false);
                }
              }}
            >
              {isDownloading ? (
                <LoaderCircle
                  className="h-5 w-5 animate-spin"
                  strokeWidth={2.2}
                />
              ) : (
                <Download className="h-5 w-5" strokeWidth={2.2} />
              )}
            </button>
          ) : null}
        </div>
      </div>
    </article>
  );
}

export function ComingSoonRecommendedCard({
  visualIndex = 0,
}: {
  visualIndex?: number;
}) {
  const cover =
    officialRecommendationCoverFallbacks[
      visualIndex % officialRecommendationCoverFallbacks.length
    ];

  return (
    <article
      className={`${CARD_CLASS} cursor-default opacity-95`}
      aria-label="即将到来"
    >
      <div className="relative block h-[108px] overflow-hidden bg-black md:aspect-[246.4/138.6] md:h-auto">
        <img
          src={cover}
          alt=""
          className="h-full w-full object-cover opacity-75 grayscale-[15%]"
          loading="lazy"
        />
        <span className="absolute left-3 top-3 rounded-md bg-ark-gold px-2.5 py-1 text-xs font-semibold text-black">
          即将到来
        </span>
      </div>
      <div className="flex min-h-[131px] flex-1 flex-col p-4 pt-3 md:min-h-[121px]">
        <div className="text-[15px] font-semibold leading-[21.72px] text-white line-clamp-2 md:text-base md:font-bold md:leading-snug">
          即将到来
        </div>
        <div className="mt-auto pt-4 text-xs text-ark-muted">
          更多内容准备中
        </div>
      </div>
    </article>
  );
}
