"use client";

import Link from "next/link";
import { useEffect, useState, useTransition, type FormEvent } from "react";
import { extractYoutubeVideoId, fetchYoutubeTitle } from "@/lib/youtube";
import { shareStatusToMember } from "@/lib/messages/actions";

const STORY_DURATION_S = 40;

type StatusItem = {
  id: string;
  userId: string;
  thumbUrl: string;
  altText: string | null;
  youtubeUrl: string | null;
  youtubeTitle: string | null;
  taggedUser: { username: string; fullName: string } | null;
  user: { profile: { username: string; fullName: string } | null };
};

export function StatusStoryBar({ statuses }: { statuses: StatusItem[] }) {
  const items = statuses.filter((s): s is StatusItem & { user: { profile: NonNullable<StatusItem["user"]["profile"]> } } =>
    Boolean(s.user.profile)
  );

  // Avatar şeridi için kullanıcı başına tek bubble — düz listedeki ilk görülen segment sırası korunur.
  const userBubbles: { userId: string; thumbUrl: string; fullName: string; firstIndex: number }[] = [];
  const seenUsers = new Set<string>();
  items.forEach((status, index) => {
    if (seenUsers.has(status.userId)) return;
    seenUsers.add(status.userId);
    userBubbles.push({ userId: status.userId, thumbUrl: status.thumbUrl, fullName: status.user.profile.fullName, firstIndex: index });
  });

  const [activeIndex, setActiveIndex] = useState<number | null>(null);
  const [paused, setPaused] = useState(false);
  const [pausedResetForIndex, setPausedResetForIndex] = useState<number | null>(null);
  const [shareOpen, setShareOpen] = useState(false);
  const [shareUsername, setShareUsername] = useState("");
  const [shareResult, setShareResult] = useState<string | null>(null);
  const [sharePending, startShareTransition] = useTransition();

  // Yeni bir duruma geçildiğinde oynatma/duraklatma ve paylaşım paneli sıfırlansın — render
  // sırasında state eşitleyen resmi React deseni (bkz. "Adjusting state when a prop changes").
  if (activeIndex !== pausedResetForIndex) {
    setPausedResetForIndex(activeIndex);
    setPaused(false);
    setShareOpen(false);
    setShareResult(null);
    setShareUsername("");
  }

  function advance() {
    setActiveIndex((i) => (i !== null && i + 1 < items.length ? i + 1 : null));
  }

  function goBack() {
    setActiveIndex((i) => (i === null ? null : Math.max(i - 1, 0)));
  }

  useEffect(() => {
    if (activeIndex === null) return;
    function onKeyDown(e: KeyboardEvent) {
      if (e.key === "Escape") setActiveIndex(null);
      if (e.key === "ArrowRight") advance();
      if (e.key === "ArrowLeft") goBack();
    }
    window.addEventListener("keydown", onKeyDown);
    return () => window.removeEventListener("keydown", onKeyDown);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activeIndex]);

  const active = activeIndex !== null ? items[activeIndex] : null;
  const activeVideoId = active?.youtubeUrl ? extractYoutubeVideoId(active.youtubeUrl) : null;
  const knownTitle = active?.youtubeTitle ?? null;

  const [liveTitle, setLiveTitle] = useState<string | null>(null);
  const [titleFetchAttempted, setTitleFetchAttempted] = useState(false);
  const [titleFetchForVideo, setTitleFetchForVideo] = useState<string | null>(null);

  if (activeVideoId !== titleFetchForVideo) {
    setTitleFetchForVideo(activeVideoId);
    setLiveTitle(null);
    setTitleFetchAttempted(false);
  }

  useEffect(() => {
    if (!activeVideoId || knownTitle) return;
    let cancelled = false;
    fetchYoutubeTitle(activeVideoId).then((title) => {
      if (cancelled) return;
      setLiveTitle(title);
      setTitleFetchAttempted(true);
    });
    return () => {
      cancelled = true;
    };
  }, [activeVideoId, knownTitle]);

  if (items.length === 0) return null;

  function submitShare(e: FormEvent) {
    e.preventDefault();
    if (!active || !shareUsername.trim()) return;
    startShareTransition(async () => {
      const result = await shareStatusToMember(active.id, shareUsername);
      setShareResult(result?.message ?? null);
      if (result?.message === "Durum gönderildi.") {
        setShareUsername("");
        setShareOpen(false);
      }
    });
  }

  const userSegments = active ? items.filter((i) => i.userId === active.userId) : [];
  const segmentIndexInUser = active ? userSegments.findIndex((s) => s.id === active.id) : -1;

  return (
    <>
      <div className="mb-4 flex items-center gap-2 text-[12.5px] font-bold uppercase tracking-wide text-accent">
        <span className="relative flex h-2.5 w-2.5">
          <span className="ping-soft absolute inline-flex h-full w-full rounded-full bg-accent" />
          <span className="relative inline-flex h-2.5 w-2.5 rounded-full bg-accent" />
        </span>
        Canlı Durumlar
      </div>
      {/* overflow-y-visible burada zorunlu: overflow-x'i visible dışında bir şeye ayarlamak,
          overflow-y açıkça belirtilmezse tarayıcının onu da "auto" yapmasına yol açıyor (CSS
          Overflow spesifikasyonu) — bu da dönen halkanın çapraz açılardaki daha büyük sınır
          kutusunun üstten/alttan kırpılmasına (yuvarlaklığın bozulmuş görünmesine) neden oluyordu. */}
      <div className="mb-8 flex gap-7 overflow-x-auto overflow-y-visible pb-3">
        {userBubbles.map((bubble) => (
          <button
            key={bubble.userId}
            type="button"
            onClick={() => setActiveIndex(bubble.firstIndex)}
            className="group relative flex shrink-0 flex-col items-center gap-2.5"
          >
            {/* Hem sürekli dönüş hem de hover'da büyüme, border-radius+overflow-hidden kırpması
                olan bir elemanı `transform` (rotate veya scale) ile hareket ettirmenin GPU katman
                birleştirmesinde gradyanın/halkanın belirli bölgelerinin hiç boyanmamasına yol
                açtığı ölçülüp doğrulanmış gerçek bir tarayıcı hatası yüzünden hiç `transform`
                kullanmıyor: dönüş .story-ring'in arka plan gradyanının açısını değiştirerek
                (globals.css'teki --ring-angle), büyüme ise kırpma katmanının width/height'ını
                gerçekten değiştirerek (transform: scale DEĞİL) yapılıyor — ikisi de normal
                boyama/layout hattından geçtiği için bu hata kategorisine hiç girmiyor. */}
            <span className="story-glow relative inline-block rounded-full">
              <span className="relative block h-24 w-24 overflow-hidden rounded-full transition-[width,height] duration-200 ease-out group-hover:h-28 group-hover:w-28">
                <span className="story-ring absolute inset-0" />
                <span className="absolute inset-[3.5px] overflow-hidden rounded-full border-2 border-bg">
                  {/* eslint-disable-next-line @next/next/no-img-element -- yerel diskten servis edilen kullanıcı içeriği */}
                  <img src={bubble.thumbUrl} alt={bubble.fullName} className="h-full w-full rounded-full object-cover" />
                </span>
              </span>
            </span>
            <span className="absolute right-1 top-1 h-4 w-4 rounded-full border-2 border-bg bg-green-500" title="Aktif" />
            <span className="max-w-[96px] truncate text-[13px] font-semibold text-text-muted group-hover:text-accent">
              {bubble.fullName.split(" ")[0]}
            </span>
          </button>
        ))}
      </div>

      {active && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/85 p-4"
          onClick={() => setActiveIndex(null)}
        >
          <div
            className="relative flex max-h-[90vh] w-full max-w-sm flex-col overflow-y-auto rounded-2xl bg-black shadow-2xl"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="flex shrink-0 gap-1 px-3 pt-3">
              {userSegments.map((segment, i) => (
                <div key={segment.id} className="h-[3px] flex-1 overflow-hidden rounded-full bg-white/25">
                  {i < segmentIndexInUser && <div className="h-full w-full bg-white" />}
                  {i === segmentIndexInUser && (
                    <div
                      key={active.id}
                      className="story-progress-fill h-full bg-white"
                      style={{ animationDuration: `${STORY_DURATION_S}s`, animationPlayState: paused ? "paused" : "running" }}
                      onAnimationEnd={advance}
                    />
                  )}
                </div>
              ))}
            </div>

            <div className="relative shrink-0">
              {/* eslint-disable-next-line @next/next/no-img-element -- yerel diskten servis edilen kullanıcı içeriği */}
              <img src={active.thumbUrl} alt={active.altText ?? ""} className="max-h-[60vh] w-full object-contain" />

              <div className="absolute inset-x-0 top-0 flex items-start justify-between bg-gradient-to-b from-black/70 to-transparent p-4">
                <div>
                  <Link
                    href={`/profil/${active.user.profile.username}`}
                    className="text-[13.5px] font-semibold text-white hover:underline"
                  >
                    {active.user.profile.fullName}
                  </Link>
                  {active.taggedUser && (
                    <div className="text-[11px] text-white/75">
                      ile{" "}
                      <Link href={`/profil/${active.taggedUser.username}`} className="font-semibold hover:underline">
                        @{active.taggedUser.username}
                      </Link>
                    </div>
                  )}
                </div>
                <button type="button" onClick={() => setActiveIndex(null)} className="p-1 text-white/80 hover:text-white">
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
                    <path d="M18 6L6 18M6 6l12 12" />
                  </svg>
                </button>
              </div>
            </div>

            <div className="flex shrink-0 items-center gap-3 border-t border-white/10 bg-black px-4 py-3">
              <button
                type="button"
                onClick={() => setPaused((p) => !p)}
                className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-accent text-white hover:bg-accent-dark"
                title={paused ? "Oynat" : "Duraklat"}
              >
                {paused ? (
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
                    <path d="M7 5v14l12-7z" />
                  </svg>
                ) : (
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
                    <rect x="6" y="5" width="4" height="14" rx="1" />
                    <rect x="14" y="5" width="4" height="14" rx="1" />
                  </svg>
                )}
              </button>

              <div className="min-w-0 flex-1">
                {activeVideoId ? (
                  <>
                    <div className="flex items-center gap-2 text-[10.5px] font-bold uppercase tracking-wide text-accent">
                      {!paused && (
                        <span className="flex h-2.5 items-end gap-[2px]">
                          <span className="eq-bar h-full w-[2.5px] bg-accent" style={{ animationDelay: "0ms" }} />
                          <span className="eq-bar h-full w-[2.5px] bg-accent" style={{ animationDelay: "150ms" }} />
                          <span className="eq-bar h-full w-[2.5px] bg-accent" style={{ animationDelay: "300ms" }} />
                        </span>
                      )}
                      Şimdi Çalıyor
                    </div>
                    <p className="truncate text-[12.5px] text-white/85">
                      {knownTitle ?? liveTitle ?? (titleFetchAttempted ? "Bilinmeyen parça" : "Parça bilgisi yükleniyor...")}
                    </p>
                  </>
                ) : (
                  <p className="truncate text-[12px] text-white/50">{active.user.profile.fullName} bir durum paylaştı</p>
                )}
              </div>

              <button
                type="button"
                onClick={() => {
                  setShareOpen((v) => !v);
                  if (!shareOpen) setPaused(true);
                }}
                className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-white/10 text-white hover:bg-white/20"
                title="Paylaş"
              >
                <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
                  <path d="M22 2L11 13" />
                  <path d="M22 2l-7 20-4-9-9-4 20-7z" />
                </svg>
              </button>

              {activeVideoId && !paused && (
                <iframe
                  key={activeVideoId}
                  className="h-0 w-0 overflow-hidden opacity-0"
                  src={`https://www.youtube-nocookie.com/embed/${activeVideoId}?autoplay=1`}
                  title="Durum müziği"
                  allow="autoplay; encrypted-media"
                />
              )}
            </div>

            {shareOpen && (
              <form onSubmit={submitShare} className="flex shrink-0 items-center gap-2 border-t border-white/10 bg-black px-4 py-3">
                <input
                  type="text"
                  value={shareUsername}
                  onChange={(e) => setShareUsername(e.target.value)}
                  placeholder="@kullaniciadi"
                  className="flex-1 rounded-lg border border-white/20 bg-white/5 px-3 py-2 text-[13px] text-white outline-none placeholder:text-white/40 focus:border-accent"
                />
                <button
                  type="submit"
                  disabled={sharePending}
                  className="rounded-lg bg-accent px-3.5 py-2 text-[12.5px] font-semibold text-white hover:bg-accent-dark disabled:opacity-60"
                >
                  {sharePending ? "..." : "Gönder"}
                </button>
              </form>
            )}
            {shareResult && <p className="shrink-0 bg-black px-4 pb-3 text-[11.5px] text-white/60">{shareResult}</p>}

            {activeIndex! > 0 && (
              <button
                type="button"
                onClick={goBack}
                className="absolute left-2 top-1/2 -translate-y-1/2 rounded-full bg-black/40 p-2 text-white hover:bg-black/60"
              >
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
                  <path d="M15 18l-6-6 6-6" />
                </svg>
              </button>
            )}
            {activeIndex! < items.length - 1 && (
              <button
                type="button"
                onClick={advance}
                className="absolute right-2 top-1/2 -translate-y-1/2 rounded-full bg-black/40 p-2 text-white hover:bg-black/60"
              >
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
                  <path d="M9 18l6-6-6-6" />
                </svg>
              </button>
            )}
          </div>
        </div>
      )}
    </>
  );
}
