"use client";

import { useState, useEffect } from "react";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { ArrowLeft, Play, CheckCircle2, ShoppingCart, Eye, Heart, AlertCircle, Loader2 } from "lucide-react";
import { rentService, type RentItem } from "@/services/rentService";
import { PaymentModal, type PaymentContext } from "@/components/payment/PaymentModal";
import { useAppDispatch } from "@/store/hooks";
import { selectRentItem } from "@/store/slices/rentSlice";
import { useGeneralSettings } from "@/lib/GeneralSettingsContext";

function RentItemCard({ item, onRent }: { item: RentItem; onRent: (item: RentItem) => void }) {
  const [hovered, setHovered] = useState(false);
  const dispatch = useAppDispatch();
  const router   = useRouter();
  const { settings } = useGeneralSettings();
  const sym = settings?.currencySymbol ?? "$";

  const handleWatch = () => {
    if (!item.isOwned) return;
    dispatch(selectRentItem(item));
    router.push(`/rent/play/${item.id}`);
  };

  return (
    <div
      className="group rounded-2xl overflow-hidden cursor-pointer transition-all duration-200"
      onClick={item.isOwned ? handleWatch : undefined}
      style={{
        background: "var(--card)",
        border: item.isOwned ? "1px solid rgba(var(--accent-gold-rgb),0.3)" : "1px solid var(--border)",
        boxShadow: hovered ? "0 12px 32px rgba(0,0,0,0.5)" : "0 2px 12px rgba(0,0,0,0.2)",
        transform: hovered ? "translateY(-2px)" : "none",
        animation: "rsd-card-in 0.4s ease both",
      }}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
    >
      <div className="relative" style={{ aspectRatio: "16/9", background: "var(--deep)" }}>
        {item.thumbnail ? (
          <Image src={item.thumbnail} alt={item.title} fill className="object-cover" unoptimized sizes="(max-width: 640px) 100vw, 50vw" />
        ) : null}
        <div className="absolute inset-0 pointer-events-none" style={{ background: "linear-gradient(to top,rgba(0,0,0,0.7) 0%,transparent 55%)" }} />

        {/* Owned badge */}
        {item.isOwned ? (
          <div className="absolute top-2 left-2 flex items-center gap-1 px-2 py-0.5 rounded-full" style={{ background: "rgba(var(--accent-gold-rgb),0.9)" }}>
            <CheckCircle2 size={10} color="#000" strokeWidth={2.5} />
            <span className="text-[9px] font-black text-black">Owned</span>
          </div>
        ) : (
          <div className="absolute top-2 left-2 px-2 py-0.5 rounded-full" style={{ background: "rgba(var(--accent-gold-rgb),0.9)" }}>
            <span className="text-[9px] font-black text-black">{sym}{item.rentPrice}</span>
          </div>
        )}

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

        {/* Play overlay */}
        <div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
          <div className="w-12 h-12 rounded-full flex items-center justify-center" style={{ background: "rgba(var(--accent-rgb),0.92)", boxShadow: "0 4px 20px rgba(var(--accent-rgb),0.5)" }}>
            <Play size={18} fill="white" strokeWidth={0} className="ml-0.5" />
          </div>
        </div>
      </div>

      <div className="p-3">
        <p className="text-[12px] font-semibold line-clamp-2 leading-snug" style={{ color: "var(--text-primary)" }}>{item.title}</p>
        <div className="flex items-center gap-3 mt-2 flex-wrap">
          <span className="flex items-center gap-1 text-[10px]" style={{ color: "#666" }}><Eye size={10} /> {item.views}</span>
          <span className="flex items-center gap-1 text-[10px]" style={{ color: "#666" }}><Heart size={10} /> {item.likes}</span>
          <span className="text-[10px]" style={{ color: "#888" }}>{item.channelName}</span>
        </div>
        {!item.isOwned && (
          <button
            onClick={(e) => { e.stopPropagation(); onRent(item); }}
            className="mt-3 w-full h-8 rounded-xl text-[11px] font-black text-black flex items-center justify-center gap-1.5 transition-all active:scale-95"
            style={{ background: "linear-gradient(135deg,var(--accent-gold),var(--accent))", boxShadow: "0 2px 12px rgba(var(--accent-gold-rgb),0.35)" }}
          >
            <ShoppingCart size={11} strokeWidth={2.5} />
            Rent for {sym}{item.rentPrice} / {item.rentDay}d
          </button>
        )}
      </div>
    </div>
  );
}

export default function RentSectionDetailPage({ sectionId }: { sectionId: string }) {
  const router = useRouter();
  const [items, setItems] = useState<RentItem[]>([]);
  const [title, setTitle] = useState("");
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [payCtx, setPayCtx] = useState<PaymentContext | null>(null);

  useEffect(() => {
    rentService.getSectionDetail(sectionId)
      .then((section) => {
        if (!section) { setError("Section not found"); return; }
        setTitle(section.title);
        setItems(section.items);
      })
      .catch(() => setError("Failed to load."))
      .finally(() => setLoading(false));
  }, [sectionId]);

  return (
    <div style={{ minHeight: "100vh", background: "var(--bg)", paddingBottom: 80 }}>
      {/* Header */}
      <div className="sticky top-0 z-20 flex items-center gap-3 px-4" style={{ height: 52, background: "rgba(10,10,10,0.9)", backdropFilter: "blur(16px)", borderBottom: "1px solid var(--border)" }}>
        <button onClick={() => router.back()} className="w-8 h-8 rounded-full flex items-center justify-center" style={{ background: "rgba(255,255,255,0.08)" }}>
          <ArrowLeft size={16} color="#fff" strokeWidth={2} />
        </button>
        <span className="text-sm font-bold text-[#ffffff] truncate">{title || "Rent"}</span>
      </div>

      {loading ? (
        <div className="flex justify-center py-20"><Loader2 size={28} className="animate-spin" color="rgba(var(--accent-rgb),0.6)" /></div>
      ) : error ? (
        <div className="flex flex-col items-center gap-3 py-20">
          <AlertCircle size={32} color="#555" strokeWidth={1.3} />
          <p className="text-sm" style={{ color: "#888" }}>{error}</p>
          <button onClick={() => router.back()} className="px-5 py-2 rounded-full text-xs font-bold text-[#ffffff]" style={{ background: "var(--accent)" }}>Go back</button>
        </div>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 px-4 py-4">
          {items.map((item) => (
            <RentItemCard
              key={item.id}
              item={item}
              onRent={(it) => setPayCtx({ type: "rent", contentId: it.id, contentName: it.title, price: it.rentPrice })}
            />
          ))}
        </div>
      )}

      <PaymentModal
        context={payCtx}
        onClose={() => setPayCtx(null)}
        onSuccess={() => {
          const paid = payCtx?.type === "rent" ? payCtx.contentId : null;
          setPayCtx(null);
          if (paid) setItems((prev) => prev.map((it) => it.id === paid ? { ...it, isOwned: true } : it));
        }}
      />

      <style>{`
        @keyframes rsd-card-in { from{opacity:0;transform:translateY(8px)} to{opacity:1;transform:translateY(0)} }
      `}</style>
    </div>
  );
}
