"use client";
import { useState, useMemo } from "react";
import { useLocale, useTranslations } from "next-intl";
import { Maximize2, Volume2 } from "lucide-react";
import type { AuctionItem } from "../types";

type PreparedVideo = {
  id: string | number;
  url: string;
  isYoutube: boolean;
};

export default function VideosSection({ item }: { item: AuctionItem }) {
  const [expandedVideo, setExpandedVideo] = useState<string | null>(null);
  const t = useTranslations("SINGLE_AUCTION.VIDEOS");
  const locale = useLocale();

  // تحضير قائمة الفيديوهات من الـ API أو fallback
  const videos = useMemo(() => {
    const allVideos: PreparedVideo[] = [];

    // أولوية: المصفوفة العلوية videos من الريسبونس
    const topVideos = Array.isArray(item?.videos) ? item.videos : [];
    if (topVideos.length > 0) {
      topVideos.forEach((v, index) => {
        const url = typeof v === "string" ? v : v.url;
        if (!url) return;
        // Convert YouTube URLs to embed format for iframe
        let embedUrl = url;
        let isYoutube = false;
        if (url.includes("youtube.com/watch")) {
          const videoId = new URL(url).searchParams.get("v");
          if (videoId) {
            embedUrl = `https://www.youtube.com/embed/${videoId}`;
            isYoutube = true;
          }
        } else if (url.includes("youtu.be/")) {
          const videoId = url.split("youtu.be/")[1]?.split("?")[0];
          if (videoId) {
            embedUrl = `https://www.youtube.com/embed/${videoId}`;
            isYoutube = true;
          }
        } else if (url.includes("youtube.com/shorts/")) {
          const videoId = url.split("youtube.com/shorts/")[1]?.split("?")[0];
          if (videoId) {
            embedUrl = `https://www.youtube.com/embed/${videoId}`;
            isYoutube = true;
          }
        }
        allVideos.push({
          id: typeof v === "string" ? `top-${index}` : (v.id ?? `top-${index}`),
          url: embedUrl,
          isYoutube,
        });
      });
    }

    // لو عندنا فيديو واحد داخل media_files.video (إضافة منفصلة)
    if (item?.media_files?.video) {
      const videoUrl =
        typeof item.media_files.video === "string"
          ? item.media_files.video
          : item.media_files.video.url;
      // تجنب التكرار إذا كان نفس الرابط موجود مسبقًا
      if (
        videoUrl &&
        !allVideos.some((v) => v.url === videoUrl || v.url.includes(videoUrl))
      ) {
        allVideos.push({
          id: "media-video",
          url: videoUrl,
          isYoutube: false,
        });
      }
    }

    return allVideos;
  }, [item]);

  if (videos.length === 0) {
    return null;
  }

  const videosWord =
    locale === "ar"
      ? videos.length === 1
        ? "فيديو"
        : "فيديوهات"
      : videos.length === 1
        ? "Video"
        : "Videos";

  return (
    <div className="bg-white rounded-2xl border border-[#0F5132]/12 shadow-[0_12px_30px_rgba(15,81,50,0.08)] p-4 sm:p-5">
      {/* Section Header */}
      <div className="flex items-center justify-between gap-3 mb-4">
        <h3 className="text-lg font-black text-[#0b1b13] flex items-center gap-2.5">
          <span className="w-2.5 h-2.5 rounded-full bg-[#0F5132] shadow-[0_0_0_4px_rgba(15,81,50,0.14)]" />
          {t("title")}
        </h3>
        <div className="flex items-center gap-1.5 text-xs text-slate-500">
          <Volume2 className="w-4 h-4 text-[#0F5132]" />
          <span>
            {videos.length} {videosWord}
          </span>
        </div>
      </div>

      {/* Videos Grid - Direct video display without thumbnails */}
      <div className="grid gap-4">
        {videos.map((v) => (
          <div
            key={v.id}
            className={`relative rounded-2xl overflow-hidden border border-[#0F5132]/15 bg-black ${
              expandedVideo === String(v.id)
                ? "aspect-video"
                : "aspect-video max-h-[300px]"
            }`}
          >
            {v.isYoutube ? (
              <iframe
                src={v.url}
                className="w-full h-full"
                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                allowFullScreen
                title={t("thumb_alt", { id: v.id })}
              />
            ) : (
              <video
                src={v.url}
                controls
                playsInline
                className="w-full h-full object-contain"
                title={t("thumb_alt", { id: v.id })}
              >
                Your browser does not support the video tag.
              </video>
            )}

            {/* Expand button */}
            <button
              onClick={() =>
                setExpandedVideo(
                  expandedVideo === String(v.id) ? null : String(v.id),
                )
              }
              className="absolute top-3 left-3 w-8 h-8 rounded-full bg-black/60 hover:bg-black/80 text-white flex items-center justify-center transition-all backdrop-blur-sm border border-white/20"
              title={
                expandedVideo === String(v.id)
                  ? locale === "ar"
                    ? "تصغير"
                    : "Minimize"
                  : locale === "ar"
                    ? "تكبير"
                    : "Expand"
              }
            >
              <Maximize2 className="w-4 h-4" />
            </button>
          </div>
        ))}
      </div>
    </div>
  );
}
