"use client";

import Image from "next/image";
import Link from "next/link";
import { AcademyExploreItem } from "@/api/fetchAcademyExplore";
import { buildStorageUrl } from "@/components/main/BaseUrl";
import BoldIcon from "@/components/ui/BoldIcon";
import ExploreAuthor from "@/components/explore/ExploreAuthor";
import { ExploreFilterId } from "@/constants/exploreFilters";

const ASPECT_RATIOS = [
  "aspect-[2/3]",
  "aspect-[3/4]",
  "aspect-[4/5]",
  "aspect-[5/6]",
  "aspect-square",
  "aspect-[3/5]",
] as const;

function hashAspect(id: string): (typeof ASPECT_RATIOS)[number] {
  let hash = 0;
  for (let i = 0; i < id.length; i++) {
    hash = (hash + id.charCodeAt(i)) % ASPECT_RATIOS.length;
  }
  return ASPECT_RATIOS[hash];
}

function getAcademyMedia(item: AcademyExploreItem): {
  kind: "video" | "image";
  src: string;
} | null {
  const file = item.files?.[0];
  if (file?.path) {
    const src = buildStorageUrl(file.path);
    const isVideo = item.type === "video" || file.type === "video";
    return { kind: isVideo ? "video" : "image", src };
  }

  if (item.course_video) {
    return { kind: "video", src: buildStorageUrl(item.course_video) };
  }

  const imagePath = item.course_images?.[0] || item.course_image;
  if (imagePath) {
    return { kind: "image", src: buildStorageUrl(imagePath) };
  }

  return null;
}

export default function ExploreAcademyCard({
  item,
  activeFilter = "all",
  coords = null,
}: {
  item: AcademyExploreItem;
  activeFilter?: ExploreFilterId;
  coords?: { lat: number; lng: number } | null;
}) {
  const media = getAcademyMedia(item);
  if (!media || !item.courseId) return null;

  const aspect = hashAspect(item._id);
  const displayName =
    [item.first_name, item.last_name].filter(Boolean).join(" ") ||
    item.teacher_name ||
    item.user_name ||
    "آموزشگاه";

  const params = new URLSearchParams();
  params.set("type", "academy");
  params.set("filter", activeFilter);
  if (coords) {
    params.set("lat", String(coords.lat));
    params.set("lng", String(coords.lng));
  }

  return (
    <article className="mb-2 break-inside-avoid">
      <Link
        href={`/explore/${item._id}?${params.toString()}`}
        className="gentle-transition block active:scale-[0.98]"
      >
        <div
          className={`relative w-full overflow-hidden rounded-2xl bg-neutral-900 ${aspect}`}
        >
          {media.kind === "video" ? (
            <video
              src={media.src}
              preload="metadata"
              muted
              playsInline
              className="absolute inset-0 h-full w-full object-cover"
            />
          ) : (
            <Image
              src={media.src}
              alt=""
              fill
              className="object-cover"
              sizes="33vw"
            />
          )}
          <span className="absolute left-2 top-2 rounded-md bg-emerald-600/90 px-1.5 py-0.5 text-[9px] font-medium text-white backdrop-blur-sm">
            رایگان
          </span>
          {media.kind === "video" && (
            <span className="absolute bottom-2 left-2 flex h-7 w-7 items-center justify-center rounded-full bg-black/55 text-[10px] text-white backdrop-blur-sm">
              ▶
            </span>
          )}
        </div>
      </Link>

      <div className="flex items-center justify-between gap-2 px-0.5 py-1.5">
        <ExploreAuthor
          userId={item.user_id || ""}
          userName={item.user_name}
          displayName={displayName}
          profileImage={item.profile_image}
        />
        <span className="flex shrink-0 items-center gap-1 text-[10px] text-neutral-500">
          <BoldIcon name="heart" size={14} tinted className="text-[#FC8EAC]" />
          {item.likesCount ?? 0}
        </span>
      </div>
    </article>
  );
}
