"use client";
import Image from "next/image";
import Link from "next/link";
import { memo, useState } from "react";
import { MoreVertical } from "lucide-react";
import { cn } from "@/utils/cn";
import { VideoItem } from "@/types/home";
import { useAppDispatch } from "@/store/hooks";
import { stopAll } from "@/store/slices/playerSlice";
import { useRouter } from "next/navigation";
import { useSidebar } from "@/lib/SidebarContext";
import { AnimatedCard } from "@/components/motion/AnimatedCard";

function ChannelAvatar({ src, name }: { src?: string; name?: string }) {
  const [error, setError] = useState(false);
  const initial = name?.trim().charAt(0).toUpperCase() || "?";

  if (src && !error) {
    return (
      // eslint-disable-next-line @next/next/no-img-element
      <img
        src={src}
        alt={name || ""}
        onError={() => setError(true)}
        className="w-7 h-7 rounded-full object-cover shrink-0 mt-0.5"
      />
    );
  }

  return (
    <div
      className="w-7 h-7 rounded-full flex items-center justify-center text-xs font-bold shrink-0 mt-0.5"
      style={{ background: "var(--deep)", color: "var(--text-muted)" }}
    >
      {initial}
    </div>
  );
}

interface VideoCardProps {
  video: VideoItem;
  isLive?: boolean;
  viewers?: string;
  className?: string;
  /** Set true for above-the-fold cards to improve LCP */
  priority?: boolean;
}

export const VideoCard = memo(function VideoCard({
  video,
  isLive,
  viewers,
  className,
  priority = false,
}: VideoCardProps) {
  const dispatch = useAppDispatch();
  const router = useRouter();
  const { collapse } = useSidebar();

  const handlePlay = (e: React.MouseEvent) => {
    e.preventDefault();
    dispatch(stopAll());
  };

  const href =
    video.type === "short"
      ? `/reel/${video.id}`
      : video.type === "music"
        ? null
        : `/video/${video.id}`;

  const cardClass = cn(
    "group flex flex-col rounded-lg overflow-hidden cursor-pointer",
    className,
  );

  const cardStyle = {
    background: "var(--card)",
    border: isLive ? "1px solid rgba(217,48,37,0.25)" : "1px solid transparent",
    boxShadow: isLive ? "0 0 0 1px rgba(217,48,37,0.12)" : "none",
  };

  return (
    <AnimatedCard className="h-full">
      <Link href={href || ""} className={cn(cardClass, "h-full")} style={cardStyle}>
        {/* Thumbnail */}
        <div
          className="relative aspect-video overflow-hidden"
          style={{ background: "var(--deep)" }}
          onClick={() => {
            collapse();
            router.push(`/video/${video.id}`);
          }}
        >
          {video.thumbnail && (
            <Image
              src={video.thumbnail}
              alt={video.title}
              fill
              className="object-cover transition-transform duration-[280ms] ease-out group-hover:scale-[1.04]"
              sizes="(max-width: 560px) 100vw, (max-width: 980px) 50vw, (max-width: 1280px) 33vw, 25vw"
              unoptimized
              priority={priority}
            />
          )}
          <div
            className="absolute inset-0 pointer-events-none"
            style={{
              background:
                "linear-gradient(180deg, rgba(0,0,0,0) 55%, rgba(0,0,0,0.55) 100%)",
            }}
          />

          {/* Play overlay */}
          <button
            onClick={handlePlay}
            className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-200"
          >
            <span
              className="w-12 h-12 rounded-full flex items-center justify-center border"
              style={{
                background: "rgba(var(--accent-rgb),0.85)",
                backdropFilter: "blur(2px)",
                borderColor: "rgba(255,255,255,0.18)",
              }}
            >
              <svg viewBox="0 0 24 24" width="18" height="18" fill="#fff">
                <path d="M8 5v14l11-7z" />
              </svg>
            </span>
          </button>

          {/* Badges */}
          {video.isPremium && (
            <span
              className="absolute top-2 left-2 text-[#ffffff] text-[8px] font-bold uppercase px-1.5 py-0.5 rounded-sm tracking-widest"
              style={{ background: "var(--accent)" }}
            >
              4K
            </span>
          )}
          {isLive && (
            <span
              className="absolute top-2 left-2 text-[#ffffff] text-[8px] font-bold uppercase px-1.5 py-0.5 rounded-sm tracking-widest flex items-center gap-1"
              style={{ background: "#d93025" }}
            >
              <span
                className="dt-live-dot w-1.5 h-1.5"
                style={{ animation: "none", boxShadow: "none" }}
              />
              LIVE
            </span>
          )}
          {video.type === "short" && !isLive && (
            <span
              className="absolute top-2 left-2 text-[#ffffff] text-[8px] font-bold uppercase px-1.5 py-0.5 rounded-sm tracking-widest"
              style={{ background: "rgba(0,0,0,0.7)" }}
            >
              REEL
            </span>
          )}
          {video.type === "music" && !isLive && (
            <span
              className="absolute top-2 left-2 text-[#ffffff] text-[8px] font-bold uppercase px-1.5 py-0.5 rounded-sm tracking-widest"
              style={{ background: "rgba(var(--accent-rgb),0.85)" }}
            >
              MUSIC
            </span>
          )}

          {/* Duration / viewers */}
          {!isLive && video.type !== "music" && (
            <span
              className="absolute right-2 bottom-2 text-[#ffffff] text-[9px] font-semibold px-1 py-0.5 rounded-sm font-mono"
              style={{ background: "rgba(0,0,0,0.8)" }}
            >
              {video.duration}
            </span>
          )}
          {isLive && viewers && (
            <span
              className="absolute left-2 bottom-2 text-[#ffffff] text-[9px] font-semibold px-1.5 py-0.5 rounded-sm flex items-center gap-1"
              style={{ background: "rgba(0,0,0,0.8)" }}
            >
              <span className="w-1 h-1 rounded-full bg-red-500 inline-block" />
              {viewers}
            </span>
          )}

          {/* Progress bar on hover */}
          {!isLive && (
            <div
              className="absolute left-0 right-0 bottom-0 h-[3px] opacity-0 group-hover:opacity-100 transition-opacity"
              style={{ background: "rgba(255,255,255,0.12)" }}
            >
              <div
                className="h-full"
                style={{ background: "var(--accent)", width: "35%" }}
              />
            </div>
          )}
        </div>

        {/* Meta */}
        <div className="flex items-start gap-2 p-2.5 relative flex-1">
          <ChannelAvatar src={video.channelAvatar} name={video.channelName} />
          <div className="flex-1 min-w-0">
            <p
              className="text-xs font-medium line-clamp-2 leading-[1.4] tracking-tight overflow-hidden"
              style={{ height: "2.8em", letterSpacing: "-0.005em", color: "var(--text-muted)" }}
            >
              {video.title}
            </p>
            <p className="text-[10px] mt-1 truncate" style={{ color: "#888" }}>
              {video.channelName}
            </p>
            <p className="text-[10px] mt-0.5" style={{ color: "#666" }}>
              {video.views}
            </p>
          </div>
          <button
            className="w-5 h-5 rounded-full flex items-center justify-center absolute top-1.5 right-1 opacity-0 group-hover:opacity-100 transition-opacity"
            style={{ color: "#999" }}
            onClick={(e) => e.preventDefault()}
          >
            <MoreVertical size={13} />
          </button>
        </div>
      </Link>
    </AnimatedCard>
  );
});
