"use client";

import { useEffect, useState } from "react";
import Image from "next/image";
import { useRouter } from "next/navigation";
import {
  Clapperboard,
  Play,
  CheckCircle2,
  ShoppingCart,
  AlertCircle,
  Eye,
  Heart,
  ChevronRight,
} from "lucide-react";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { fetchRentSections, markOwned } from "@/store/slices/rentSlice";
import { PaymentModal, type PaymentContext } from "@/components/payment/PaymentModal";
import { stopAll } from "@/store/slices/playerSlice";
import { selectRentItem } from "@/store/slices/rentSlice";
import { useSidebar } from "@/lib/SidebarContext";
import { useGeneralSettings } from "@/lib/GeneralSettingsContext";
import { RentItem, RentSection } from "@/services/rentService";

/* ─────────────────────────────────────────────────────────────────────────────
   Gold price badge
───────────────────────────────────────────────────────────────────────────── */

const GOLD = "var(--accent-gold)";
const GOLD_BG = "rgba(var(--accent-gold-rgb),0.92)";
const GOLD_DARK = "#1a1200";

function PriceBadge({ price, small = false, sym = "$" }: { price: number; small?: boolean; sym?: string }) {
  return (
    <span
      className="inline-flex items-center font-black rounded-sm"
      style={{
        background: GOLD_BG,
        color: GOLD_DARK,
        padding: small ? "2px 6px" : "3px 8px",
        fontSize: small ? 9 : 10,
        letterSpacing: "0.02em",
        boxShadow: "0 2px 8px rgba(var(--accent-gold-rgb),0.4)",
      }}
    >
      {sym}{price}
    </span>
  );
}

/* ─────────────────────────────────────────────────────────────────────────────
   Rental card
───────────────────────────────────────────────────────────────────────────── */

const CARD_W = 232;
const CARD_H = 130; // 16:9

function RentCard({ item, sectionId, index, onRent }: {
  item: RentItem; sectionId: string; index: number;
  onRent: (item: RentItem) => void;
}) {
  const dispatch = useAppDispatch();
  const router   = useRouter();
  const { collapse } = useSidebar();
  const { settings } = useGeneralSettings();
  const sym = settings?.currencySymbol ?? "$";
  const [hovered, setHovered] = useState(false);
  const delay = Math.min(index * 50, 500);

  const handleWatch = () => {
    dispatch(stopAll());
    dispatch(selectRentItem(item));
    collapse();
    router.push(`/rent/play/${item.id}`);
  };

  const handleRent = (e: React.MouseEvent) => {
    e.stopPropagation();
    onRent(item);
  };

  return (
    <div
      className="shrink-0 flex flex-col group cursor-pointer"
      style={{
        width: CARD_W,
        animation: `rent-section-in 0.4s ease forwards`,
        animationDelay: `${delay}ms`,
        opacity: 0,
      }}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      onClick={item.isOwned ? handleWatch : undefined}
    >
      {/* ── Thumbnail ─────────────────────────────────────────────────── */}
      <div
        className="relative overflow-hidden rounded-xl"
        style={{ width: CARD_W, height: CARD_H, background: "var(--deep)" }}
      >
        {item.thumbnail ? (
          <Image
            src={item.thumbnail}
            alt={item.title}
            fill
            className="object-cover transition-transform duration-400"
            style={{ transform: hovered ? "scale(1.06)" : "scale(1)" }}
            unoptimized
            sizes={`${CARD_W}px`}
          />
        ) : (
          <div className="w-full h-full flex items-center justify-center">
            <Clapperboard size={28} style={{ color: "var(--accent)", opacity: 0.4 }} strokeWidth={1.5} />
          </div>
        )}

        {/* Gradient overlays */}
        <div
          className="absolute inset-0 pointer-events-none"
          style={{
            background:
              "linear-gradient(to top, rgba(0,0,0,0.88) 0%, rgba(0,0,0,0.3) 45%, rgba(0,0,0,0.05) 75%)",
          }}
        />

        {/* Price badge — top right */}
        <div className="absolute top-2 right-2 z-10">
          {item.isOwned ? (
            <span
              className="flex items-center gap-1 text-[9px] font-black px-2 py-0.5 rounded-sm"
              style={{ background: "rgba(34,197,94,0.9)", color: "white" }}
            >
              <CheckCircle2 size={8} strokeWidth={2.5} />
              OWNED
            </span>
          ) : (
            <PriceBadge price={item.rentPrice} sym={sym} />
          )}
        </div>

        {/* Duration badge — bottom right */}
        {item.duration && (
          <span
            className="absolute bottom-2 right-2 text-[9px] font-semibold px-1.5 py-0.5 rounded-sm font-mono z-10"
            style={{ background: "rgba(0,0,0,0.82)", color: "#ddd" }}
          >
            {item.duration}
          </span>
        )}

        {/* Hover overlay — Rent / Watch CTA */}
        <div
          className="absolute inset-0 flex items-center justify-center transition-opacity duration-200 z-10"
          style={{ opacity: hovered ? 1 : 0 }}
        >
          {item.isOwned ? (
            <button
              className="flex items-center gap-2 px-4 py-2 rounded-full text-[11px] font-bold text-[#ffffff] transition-all active:scale-95"
              style={{ background: "var(--accent)", boxShadow: "0 4px 20px rgba(var(--accent-rgb),0.55)" }}
              onClick={handleWatch}
            >
              <Play size={12} fill="white" strokeWidth={0} />
              Watch Now
            </button>
          ) : (
            <button
              className="flex items-center gap-2 px-4 py-2 rounded-full text-[11px] font-bold transition-all active:scale-95 disabled:opacity-60"
              style={{
                background: GOLD_BG,
                color: GOLD_DARK,
                boxShadow: "0 4px 20px rgba(var(--accent-gold-rgb),0.5)",
                animation: "gold-shimmer 2s ease-in-out infinite",
              }}
              onClick={handleRent}
            >
              <ShoppingCart size={12} strokeWidth={2} />
              {`Rent ${sym}${item.rentPrice}`}
            </button>
          )}
        </div>
      </div>

      {/* ── Meta below card ───────────────────────────────────────────── */}
      <div className="pt-2 px-0.5">
        <p className="text-[11px] font-semibold line-clamp-2 leading-snug" style={{ color: "var(--text-primary)" }}>
          {item.title}
        </p>

        <div className="flex items-center gap-2 mt-1.5 flex-wrap">
          {/* Channel */}
          <span className="text-[10px] truncate max-w-[100px]" style={{ color: "#777" }}>
            {item.channelName}
          </span>
          <span style={{ color: "#444", fontSize: 9 }}>·</span>

          {/* Views */}
          {item.views !== "0 views" && (
            <>
              <span className="flex items-center gap-0.5 text-[10px]" style={{ color: "#666" }}>
                <Eye size={9} strokeWidth={1.8} />
                {item.views}
              </span>
              <span style={{ color: "#444", fontSize: 9 }}>·</span>
            </>
          )}

          {/* Likes */}
          {parseInt(item.likes) > 0 && (
            <span className="flex items-center gap-0.5 text-[10px]" style={{ color: "#666" }}>
              <Heart size={9} strokeWidth={1.8} />
              {item.likes}
            </span>
          )}
        </div>

        {/* Category + Language + Rent info */}
        <div className="flex items-center gap-1.5 mt-1.5 flex-wrap">
          <span
            className="text-[9px] font-semibold px-1.5 py-0.5 rounded-full"
            style={{ background: "var(--btn-ghost)", color: "#666", border: "1px solid var(--btn-ghost-hover)" }}
          >
            {item.category}
          </span>
          {item.language && (
            <span className="text-[9px]" style={{ color: "#555" }}>{item.language}</span>
          )}
          {!item.isOwned && (
            <span className="text-[9px] font-bold ml-auto" style={{ color: GOLD }}>
              {sym}{item.rentPrice}
              {item.rentDay > 0 && ` / ${item.rentDay}d`}
            </span>
          )}
        </div>
      </div>
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────────────────────
   Section skeleton
───────────────────────────────────────────────────────────────────────────── */

function SectionSkeleton() {
  return (
    <div className="mb-10">
      <div className="flex items-center justify-between mb-4">
        <div className="h-4 w-32 rounded-full animate-pulse" style={{ background: "var(--card)" }} />
        <div className="h-3 w-14 rounded-full animate-pulse" style={{ background: "var(--card)" }} />
      </div>
      <div className="flex gap-4 overflow-hidden">
        {Array.from({ length: 4 }).map((_, i) => (
          <div key={i} className="shrink-0 flex flex-col gap-2 animate-pulse" style={{ width: CARD_W }}>
            <div className="rounded-xl" style={{ width: CARD_W, height: CARD_H, background: "var(--card)" }} />
            <div className="h-3 rounded-full" style={{ background: "var(--card)", width: "85%" }} />
            <div className="h-2.5 rounded-full" style={{ background: "var(--card)", width: "55%" }} />
          </div>
        ))}
      </div>
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────────────────────
   Section block
───────────────────────────────────────────────────────────────────────────── */

function RentSectionBlock({ section, sectionIndex, onRent }: {
  section: RentSection; sectionIndex: number; onRent: (item: RentItem) => void;
}) {
  const router = useRouter();
  return (
    <section
      className="mb-10"
      style={{
        animation: "rent-section-in 0.45s ease forwards",
        animationDelay: `${sectionIndex * 80}ms`,
        opacity: 0,
      }}
    >
      {/* Section header */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-2.5">
          <div
            className="w-1 h-5 rounded-full"
            style={{ background: "linear-gradient(to bottom, var(--accent), rgba(var(--accent-gold-rgb),0.7))" }}
          />
          <h2 className="text-sm font-bold tracking-tight" style={{ color: "var(--text-primary)" }}>{section.title}</h2>
          <span
            className="text-[9px] font-bold px-2 py-0.5 rounded-full"
            style={{ background: "rgba(var(--accent-gold-rgb),0.1)", color: GOLD, border: "1px solid rgba(var(--accent-gold-rgb),0.2)" }}
          >
            {section.items.length} titles
          </span>
        </div>

        {section.viewAll && (
          <button
            className="flex items-center gap-0.5 text-[11px] font-semibold transition-all active:scale-95"
            style={{ color: "var(--accent)" }}
            onClick={() => router.push(`/rent/section/${section.id}`)}
          >
            See all <ChevronRight size={12} strokeWidth={2} />
          </button>
        )}
      </div>

      {/* Horizontal scroll shelf */}
      <div className="relative">
       
        <div className="flex gap-4 overflow-x-auto scrollbar-hide pb-1">
          {section.items.map((item, i) => (
            <RentCard key={item.id} item={item} sectionId={section.id} index={i} onRent={onRent} />
          ))}
        </div>
        <div
          className="absolute right-0 top-0 bottom-0 w-8 pointer-events-none z-10"
          style={{ background: "linear-gradient(270deg, var(--bg) 30%, transparent)" }}
        />
      </div>
    </section>
  );
}

/* ─────────────────────────────────────────────────────────────────────────────
   RentPage
───────────────────────────────────────────────────────────────────────────── */

export default function RentPage() {
  const dispatch = useAppDispatch();
  const { sections, isLoading, error } = useAppSelector((s) => s.rent);
  const [payCtx, setPayCtx] = useState<PaymentContext | null>(null);

  useEffect(() => {
    dispatch(fetchRentSections(1));
  }, [dispatch]);

  /* Count owned items */
  const ownedCount = sections.flatMap((s) => s.items).filter((i) => i.isOwned).length;

  return (
    <>
      {/* ── Header ──────────────────────────────────────────────────────── */}
      <div
        className="relative px-5 pt-6 pb-5 overflow-hidden"
        style={{
          background: "linear-gradient(180deg, rgba(var(--accent-gold-rgb),0.06) 0%, transparent 100%)",
          borderBottom: "1px solid var(--border-soft)",
        }}
      >
        {/* Gold glow blob */}
        <div
          className="absolute top-0 right-0 w-48 h-48 pointer-events-none"
          style={{ background: "radial-gradient(circle, rgba(var(--accent-gold-rgb),0.08) 0%, transparent 70%)" }}
        />

        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3.5">
            <div
              className="w-11 h-11 rounded-xl flex items-center justify-center shrink-0"
              style={{ background: "rgba(var(--accent-gold-rgb),0.1)", border: "1px solid rgba(var(--accent-gold-rgb),0.22)" }}
            >
              <Clapperboard size={20} style={{ color: GOLD }} strokeWidth={1.8} />
            </div>
            <div>
              <h1 className="text-base font-black tracking-tight leading-tight" style={{ color: "var(--text-primary)" }}>
                Rent Content
              </h1>
              <p className="text-[11px] mt-0.5" style={{ color: "#666" }}>
                Premium videos — rent to watch
              </p>
            </div>
          </div>

          {/* Owned count pill */}
          {ownedCount > 0 && (
            <div
              className="flex items-center gap-1.5 px-3 py-1.5 rounded-full"
              style={{ background: "rgba(34,197,94,0.1)", border: "1px solid rgba(34,197,94,0.2)" }}
            >
              <CheckCircle2 size={12} color="#4ade80" strokeWidth={2} />
              <span className="text-[11px] font-bold" style={{ color: "#4ade80" }}>
                {ownedCount} owned
              </span>
            </div>
          )}
        </div>
      </div>

      {/* ── Content ─────────────────────────────────────────────────────── */}
      <div className="px-5 pt-6 pb-28">
        {isLoading ? (
          <>
            {Array.from({ length: 3 }).map((_, i) => <SectionSkeleton key={i} />)}
          </>
        ) : error ? (
          <div className="flex flex-col items-center justify-center py-24 gap-4">
            <AlertCircle size={36} color="#555" strokeWidth={1.2} />
            <p className="text-sm" style={{ color: "#888" }}>{error}</p>
            <button
              onClick={() => dispatch(fetchRentSections(1))}
              className="px-5 py-2 rounded-full text-xs font-bold text-[#ffffff] active:scale-95"
              style={{ background: "var(--accent)" }}
            >
              Try again
            </button>
          </div>
        ) : sections.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-24 gap-5">
            <div
              className="w-20 h-20 rounded-full flex items-center justify-center"
              style={{ background: "rgba(var(--accent-gold-rgb),0.07)", border: "1px solid rgba(var(--accent-gold-rgb),0.15)" }}
            >
              <Clapperboard size={34} style={{ color: GOLD, opacity: 0.4 }} strokeWidth={1.2} />
            </div>
            <div className="text-center">
              <p className="text-sm font-semibold" style={{ color: "var(--text-primary)" }}>No rental content available</p>
              <p className="text-xs mt-1" style={{ color: "#555" }}>Check back later for premium titles</p>
            </div>
          </div>
        ) : (
          sections.map((section, i) => (
            <RentSectionBlock
              key={section.id}
              section={section}
              sectionIndex={i}
              onRent={(item) => setPayCtx({
                type: "rent",
                contentId: item.id,
                contentName: item.title,
                price: item.rentPrice,
              })}
            />
          ))
        )}
      </div>

      <PaymentModal
        context={payCtx}
        onClose={() => setPayCtx(null)}
        onSuccess={() => {
          setPayCtx(null);
          dispatch(fetchRentSections(1));
        }}
      />
    </>
  );
}
