"use client";

import { SeriesItem } from "@/components/home/home.type";
import { Flame } from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import React, { useState } from "react";
import { ImageConstant } from "../../../constant/ImageConstant";

interface TopTenProps {
  items?: SeriesItem[];
  isLoading?: boolean;
}

const AGE_RATING_LABEL: Record<string, string> = {
  G: "All Ages",
  PG: "All Ages",
  "PG-13": "13+",
  R: "17+",
  "NC-17": "18+",
};

const resolveImage = (item: SeriesItem) => {
  const src =
    item?.thumbnail_high_3x4 ??
    item?.thumbnail_high_9x16 ??
    item?.series_thumbnail ??
    item?.thumbnail_high_1x1;

  if (!src) return ImageConstant.imagePlaceHolder;
  return src.startsWith("http")
    ? src
    : `${process.env.NEXT_PUBLIC_IMAGE_BASE_URL}/${src}`;
};

const buildMeta = (item: SeriesItem) => {
  const tags = (item?.tags ?? []).flatMap((tag) =>
    String(tag)
      .split(",")
      .map((part) => part.trim())
      .filter(Boolean)
  );

  return [
    ...tags.slice(0, 2),
    "Series",
    AGE_RATING_LABEL[item?.age_rating] ?? item?.age_rating,
  ]
    .filter(Boolean)
    .join(" · ");
};

const TopTenBadge: React.FC<{ item: SeriesItem }> = ({ item }) => {
  const tag = item?.content_tag?.name?.trim();
  if (!tag) return null;

  const isHot = ["HOT", "TRENDING"].includes(tag.toUpperCase());

  return (
    <span
      className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide ${
        isHot ? "text-white" : "bg-[#2A2124] text-white/80"
      }`}
      style={
        isHot
          ? {
              background: item?.content_tag?.color || "#ED3A57",
              color: item?.content_tag?.text_color || "#FFFFFF",
            }
          : undefined
      }
    >
      {isHot && <Flame className="h-3 w-3" aria-hidden="true" />}
      {tag}
    </span>
  );
};

const TopTenRow: React.FC<{ item: SeriesItem; rank: number }> = ({
  item,
  rank,
}) => {
  const [imgSrc, setImgSrc] = useState(resolveImage(item));

  return (
    <li>
      <Link
        href={
          item?.series_id
            ? `/series/${item.series_id}`
            : `/video/${item?.video_id}`
        }
        className="group flex items-center gap-5 border-b border-white/10 py-4 transition-colors hover:bg-white/[0.02]"
      >
        <span className="w-12 shrink-0 text-right text-[48px] md:w-14 md:text-[60px] font-extrabold leading-none tabular-nums text-white transition-colors group-hover:text-[#ED3A57]">
          {rank}
        </span>

        <span className="relative block aspect-[2/3] w-11 shrink-0 overflow-hidden rounded-md border border-white/10 md:w-12">
          <Image
            src={imgSrc}
            alt=""
            aria-hidden="true"
            fill
            sizes="48px"
            onError={() => setImgSrc(ImageConstant.imagePlaceHolder)}
            className="object-cover transition-transform duration-500 group-hover:scale-105"
          />
        </span>

        <span className="min-w-0 flex-1">
          <span className="flex flex-wrap items-center gap-2">
            <span className="truncate text-[18px] font-semibold text-white transition-colors group-hover:text-[#ED3A57]">
              {item?.title}
            </span>
            <TopTenBadge item={item} />
          </span>
          <span className="mt-1 block text-[14px] text-gray-400">
            {buildMeta(item)}
          </span>
        </span>
      </Link>
    </li>
  );
};

const TopTenRowSkeleton = () => (
  <li className="flex items-center gap-5 border-b border-white/10 py-4">
    <div className="h-12 w-12 shrink-0 animate-pulse rounded bg-gray-800 md:w-14" />
    <div className="aspect-[2/3] w-11 shrink-0 animate-pulse rounded-md bg-gray-800 md:w-12" />
    <div className="w-full">
      <div className="h-5 w-2/3 animate-pulse rounded bg-gray-800" />
      <div className="mt-2 h-4 w-1/3 animate-pulse rounded bg-gray-800" />
    </div>
  </li>
);

const TopTen: React.FC<TopTenProps> = ({ items = [], isLoading }) => {
  const topTen = items.slice(0, 10);

  if (!isLoading && topTen.length === 0) return null;

  return (
    <section
      id="top10"
      className="scroll-mt-24 border-y border-white/10 bg-[#100a0d] py-24 md:py-32"
    >
      <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
        <p className="text-xs font-bold uppercase tracking-[0.24em] text-[#ED3A57]">
          This week on ReelFlix
        </p>
        <div className="mt-3 flex flex-wrap items-end justify-between gap-4">
          <h2 className="max-w-xl text-[36px] md:text-[48px] font-extrabold leading-[1.1] tracking-tight text-white">
            The Top 10
            <br />
            everyone&apos;s binging
          </h2>
          <p className="max-w-sm text-[14px] leading-relaxed text-gray-400">
            Ranked by completed episodes per hour. Refreshes every Monday — no
            paid placement, ever.
          </p>
        </div>

        <ol className="mt-12 grid gap-x-14 gap-y-1 md:grid-cols-2">
          {isLoading
            ? Array.from({ length: 10 })?.map((_, index) => (
                <TopTenRowSkeleton key={index} />
              ))
            : topTen?.map((item, index) => (
                <TopTenRow
                  key={item?.series_id ?? index}
                  item={item}
                  rank={index + 1}
                />
              ))}
        </ol>
      </div>
    </section>
  );
};

export default TopTen;
