"use client";

import Image from "next/image";
import { cn } from "@/lib/utils";
import { Crown, Star, Subtitles, Mic2, Play } from "lucide-react";
import { toPersianDigits } from "@/lib/poster";
import { useAppStore, type ViewName } from "@/lib/store";

export interface PosterItem {
  slug: string;
  type: "movie" | "series";
  title: string;
  persianTitle: string;
  poster: string | null;
  backdrop?: string | null;
  gradient: [string, string];
  imdbRating: number;
  quality: string;
  isDubbed: boolean;
  hasSubtitle: boolean;
  isPremium: boolean;
  isNew?: boolean;
  isTrending?: boolean;
  duration?: number;
  totalSeasons?: number;
  releaseYear: number;
  genres?: { persianName: string }[];
  reason?: string;
  progress?: number;
}

const QUALITY_LABEL: Record<string, string> = {
  "2160p": "4K",
  "1440p": "2K",
  "1080p": "FHD",
  "720p": "HD",
  "480p": "SD",
};

interface PosterProps {
  item: PosterItem;
  className?: string;
  showReason?: boolean;
  onPlay?: () => void;
}

export function Poster({ item, className, showReason, onPlay }: PosterProps) {
  const openDetail = useAppStore((s) => s.openDetail);
  const gradient = `linear-gradient(150deg, ${item.gradient[0]} 0%, ${item.gradient[1]} 100%)`;
  const hasImage = !!item.poster;

  return (
    <div
      className={cn(
        "group relative aspect-[2/3] rounded-xl overflow-hidden cursor-pointer card-lift bg-card",
        className,
      )}
      onClick={() => { if (onPlay) onPlay(); else openDetail(item.type, item.slug); }}
      role="button"
      tabIndex={0}
      onKeyDown={(e) => { if (e.key === "Enter") { if (onPlay) onPlay(); else openDetail(item.type, item.slug); } }}
    >
      {hasImage ? (
        <Image
          src={item.poster!}
          alt={item.persianTitle}
          fill
          unoptimized
          sizes="(max-width:768px) 50vw, (max-width:1280px) 25vw, 220px"
          className="object-cover transition-transform duration-500 group-hover:scale-110"
        />
      ) : (
        <div className="absolute inset-0" style={{ background: gradient }}>
          <div className="absolute inset-0 opacity-30 mix-blend-overlay" style={{ background: "radial-gradient(circle at 30% 20%, rgba(255,255,255,0.4), transparent 50%)" }} />
          <div className="absolute inset-x-0 bottom-0 h-1/2 bg-gradient-to-t from-black/70 to-transparent" />
          <div className="absolute inset-0 flex flex-col justify-between p-3">
            <div className="flex items-start justify-between">
              <span className="text-[10px] font-bold tracking-widest text-white/70">PEEPBOX</span>
              <span className="text-[10px] text-white/50">{toPersianDigits(item.releaseYear)}</span>
            </div>
            <div>
              <div className="text-lg font-black leading-tight text-white drop-shadow-lg line-clamp-3">
                {item.persianTitle}
              </div>
              <div className="mt-1 text-[10px] text-white/60 line-clamp-1">{item.title}</div>
            </div>
          </div>
        </div>
      )}

      <div className="absolute top-2 right-2 left-2 flex items-start justify-between gap-1 pointer-events-none">
        <div className="flex flex-col gap-1">
          {item.isPremium && (
            <span className="inline-flex items-center gap-1 rounded-md bg-gradient-brand px-1.5 py-0.5 text-[9px] font-bold text-white shadow">
              <Crown className="h-2.5 w-2.5" /> VIP
            </span>
          )}
          {item.isNew && (
            <span className="rounded-md bg-success px-1.5 py-0.5 text-[9px] font-bold text-white shadow">جدید</span>
          )}
        </div>
        <span className="rounded-md bg-black/60 backdrop-blur px-1.5 py-0.5 text-[9px] font-bold text-white">
          {QUALITY_LABEL[item.quality] ?? item.quality}
        </span>
      </div>

      <div className="absolute bottom-2 right-2 flex items-center gap-1 rounded-md bg-black/70 backdrop-blur px-1.5 py-0.5 text-[10px] font-bold text-warning">
        <Star className="h-2.5 w-2.5 fill-warning" />
        {toPersianDigits(item.imdbRating.toFixed(1))}
      </div>

      <div className="absolute bottom-2 left-2 flex gap-1">
        {item.isDubbed && (
          <span className="flex items-center gap-0.5 rounded bg-black/70 backdrop-blur px-1 py-0.5 text-[9px] font-semibold text-white">
            <Mic2 className="h-2.5 w-2.5" /> دوبله
          </span>
        )}
        {item.hasSubtitle && !item.isDubbed && (
          <span className="flex items-center gap-0.5 rounded bg-black/70 backdrop-blur px-1 py-0.5 text-[9px] font-semibold text-white">
            <Subtitles className="h-2.5 w-2.5" /> زیرنویس
          </span>
        )}
      </div>

      <div className="absolute inset-0 bg-gradient-to-t from-black/95 via-black/40 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 flex flex-col justify-end p-3">
        <button
          className="mb-2 flex items-center justify-center gap-1.5 rounded-lg bg-primary py-2 text-xs font-bold text-white hover:bg-primary/90 transition w-full"
          onClick={(e) => { e.stopPropagation(); if (onPlay) onPlay(); else useAppStore.getState().navigate("watch" as ViewName, { contentType: item.type, contentSlug: item.slug }); }}
        >
          <Play className="h-3.5 w-3.5 fill-white" /> پخش
        </button>
        <div className="text-xs font-bold text-white line-clamp-1">{item.persianTitle}</div>
        <div className="mt-0.5 flex flex-wrap gap-1 text-[9px] text-white/70">
          {item.genres?.slice(0, 2).map((g) => (
            <span key={g.persianName}>{g.persianName}</span>
          ))}
          {item.duration && <span>• {toPersianDigits(item.duration)} دقیقه</span>}
        </div>
        {showReason && item.reason && (
          <div className="mt-1 text-[10px] text-accent line-clamp-2">✨ {item.reason}</div>
        )}
      </div>

      {typeof item.progress === "number" && item.progress > 0 && (
        <div className="absolute bottom-0 inset-x-0 h-1 bg-black/50">
          <div className="h-full bg-primary" style={{ width: `${item.progress}%` }} />
        </div>
      )}
    </div>
  );
}
