"use client";

import { SeriesItem } from "@/components/home/home.type";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useCategoryList } from "@/state/categories/categories.action";
import { useLibrarySeries } from "@/state/home/home.action";
import { useSettingsStore } from "@/state/store/settings.store";
import { Search } from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import React, { useMemo, useState } from "react";
import { ImageConstant } from "../../../constant/ImageConstant";

const ALL_SHELF = "All";
const MAX_ITEMS = 24;

const resolvePoster = (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 LibraryCard: React.FC<{ item: SeriesItem }> = ({ item }) => {
  const [imgSrc, setImgSrc] = useState(resolvePoster(item));
  const tag = item?.content_tag?.name?.trim();
  const isHot = ["HOT", "TRENDING"].includes((tag ?? "").toUpperCase());

  return (
    <Link
      href={
        item?.series_id
          ? `/series/${item.series_id}`
          : `/video/${item?.video_id}`
      }
      className="group relative block overflow-hidden rounded-xl border border-white/10 bg-[#141014] transition-all duration-300 hover:-translate-y-1 hover:shadow-[0_20px_40px_-16px_rgba(0,0,0,0.7)]"
    >
      <div className="relative aspect-[2/3] overflow-hidden bg-[#1c1418]">
        <Image
          src={imgSrc}
          alt={`Poster for ${item?.title ?? "series"}`}
          fill
          sizes="(max-width: 640px) 50vw, (max-width: 1024px) 25vw, 16vw"
          onError={() => setImgSrc(ImageConstant.imagePlaceHolder)}
          className="object-cover transition-transform duration-500 ease-out group-hover:scale-105"
        />

        {tag && (
          <span
            className={`absolute left-2.5 top-2.5 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
            }
          >
            {tag}
          </span>
        )}

        <div
          aria-hidden="true"
          className="absolute inset-x-0 bottom-0 h-3/5"
          style={{
            background:
              "linear-gradient(180deg, rgba(10,7,9,0) 0%, rgba(10,7,9,0.55) 45%, rgba(10,7,9,0.95) 100%)",
          }}
        />

        <div className="absolute inset-x-0 bottom-0 p-4">
          <h3 className="line-clamp-2 text-[14px] font-semibold leading-snug text-white">
            {item?.title}
          </h3>
          <p className="mt-1 text-[12px] tabular-nums text-white/60">
            {item?.total_episodes ? `${item.total_episodes} eps` : "Feature"}
          </p>
        </div>
      </div>
    </Link>
  );
};

const LibraryCardSkeleton = () => (
  <div className="aspect-[2/3] w-full animate-pulse rounded-xl bg-gray-800" />
);

const Library = () => {
  const { language, country, hasHydrated } = useSettingsStore();
  const [shelf, setShelf] = useState(ALL_SHELF);
  const [search, setSearch] = useState("");

  const { data: categoryList = [] } = useCategoryList();
  const { data, isLoading } = useLibrarySeries(
    {
      category: shelf === ALL_SHELF ? "" : shelf,
      languageId: language?.language_id,
      countryId: country?.country_id,
    },
    { enabled: hasHydrated && !!language?.language_id }
  );

  const items = useMemo(() => {
    const term = search.trim().toLowerCase();
    const list = data?.items ?? [];

    if (!term) return list;
    return list.filter(
      (item) =>
        item?.title?.toLowerCase().includes(term) ||
        (item?.tags ?? []).some((tag: string) =>
          String(tag).toLowerCase().includes(term)
        )
    );
  }, [data?.items, search]);

  const visibleItems = items.slice(0, MAX_ITEMS);

  return (
    <section id="browse" className="scroll-mt-24 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]">
          The library
        </p>
        <div className="mt-3 flex flex-wrap items-end justify-between gap-6">
          <h2 className="max-w-xl text-[36px] md:text-[48px] font-extrabold leading-[1.1] tracking-tight text-white">
            Find your next obsession
          </h2>
          <div className="flex items-center gap-3">
            <div className="relative">
              <Search
                className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"
                aria-hidden="true"
              />
              <label htmlFor="library-search" className="sr-only">
                Search shows and genres
              </label>
              <Input
                id="library-search"
                value={search}
                onChange={(event) => setSearch(event.target.value)}
                placeholder="Search titles or genres…"
                className="w-64 border-white/15 bg-[#141014] pl-9 text-white placeholder:text-gray-500"
              />
            </div>
            <p
              className="hidden text-sm tabular-nums text-gray-400 sm:block"
              aria-live="polite"
            >
              {items.length} shows
            </p>
          </div>
        </div>

        <div
          className="no-scrollbar mt-8 flex gap-2 overflow-x-auto pb-1"
          role="tablist"
          aria-label="Filter by shelf"
        >
          {[
            { key: ALL_SHELF, label: ALL_SHELF },
            ...categoryList?.map((category) => ({
              key: category?.camel_case_name,
              label: category?.name,
            })),
          ]?.map((option) => (
            <button
              key={option.key}
              type="button"
              role="tab"
              aria-selected={shelf === option.key}
              onClick={() => setShelf(option.key)}
              className={`shrink-0 cursor-pointer rounded-full border px-4 py-2 text-sm font-medium capitalize transition-colors ${
                shelf === option.key
                  ? "border-[#ED3A57] bg-[#ED3A57] text-white"
                  : "border-white/15 bg-[#141014] text-gray-400 hover:border-[#ED3A57]/50 hover:text-white"
              }`}
            >
              {option.label}
            </button>
          ))}
        </div>

        {isLoading ? (
          <div className="mt-10 grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 lg:gap-5">
            {Array.from({ length: 12 })?.map((_, index) => (
              <LibraryCardSkeleton key={index} />
            ))}
          </div>
        ) : visibleItems.length === 0 ? (
          <div className="mt-12 rounded-xl border border-dashed border-white/15 bg-[#141014] p-12 text-center">
            <p className="text-lg font-semibold text-white">
              {search ? `No matches for "${search}"` : "Nothing here yet"}
            </p>
            <p className="mt-2 text-sm text-gray-400">
              Try a mood instead — &quot;revenge&quot;, &quot;dragon&quot;,
              &quot;billionaire&quot;, &quot;second chance&quot;.
            </p>
            <Button
              variant="outline"
              className="mt-6 cursor-pointer border-white/15 bg-transparent text-white hover:bg-white/10"
              onClick={() => {
                setSearch("");
                setShelf(ALL_SHELF);
              }}
            >
              Reset filters
            </Button>
          </div>
        ) : (
          <>
            <div className="mt-10 grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 lg:gap-5">
              {visibleItems?.map((item, index) => (
                <LibraryCard key={item?.series_id ?? index} item={item} />
              ))}
            </div>

            {items.length > MAX_ITEMS && (
              <p className="mt-8 text-center text-sm text-gray-400">
                Showing {MAX_ITEMS} of {items.length} — refine with a shelf or
                search term to narrow it down.
              </p>
            )}
          </>
        )}
      </div>
    </section>
  );
};

export default Library;
