"use client";

import { useEffect, useState } from "react";
import {
  collection,
  getDocs,
  limit,
  query,
  where,
  type QueryDocumentSnapshot,
  type DocumentData,
} from "firebase/firestore";
import Link from "next/link";
import Image from "next/image";
import { getDb, firebaseConfigured } from "@/lib/firebase";
import { COLLECTIONS } from "@/lib/firestore-paths";
import { slugify } from "@/lib/slug";
import type { BlogPost } from "@/types/models";
import { FadeIn } from "@/components/motion/FadeIn";
import { ArrowLeft } from "lucide-react";
import { publicImageSrc } from "@/lib/public-image";

function safeDecodeSegment(segment: string) {
  try {
    return decodeURIComponent(segment);
  } catch {
    return segment;
  }
}

export function BlogPostView({ slug }: { slug: string }) {
  const [post, setPost] = useState<BlogPost | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!firebaseConfigured) {
      setPost(null);
      setLoading(false);
      return;
    }
    const db = getDb();
    if (!db) {
      setLoading(false);
      return;
    }
    let cancelled = false;
    (async () => {
      try {
        const decoded = safeDecodeSegment(slug).trim();
        if (!decoded) {
          setPost(null);
          return;
        }
        const candidates = [...new Set([decoded, slugify(decoded)].filter((s) => s.length > 0))];
        let found: QueryDocumentSnapshot<DocumentData> | null = null;
        for (const s of candidates) {
          const q = query(collection(db, COLLECTIONS.posts), where("slug", "==", s), limit(1));
          const snap = await getDocs(q);
          if (!snap.empty) {
            found = snap.docs[0]!;
            break;
          }
        }
        if (cancelled) return;
        if (found) {
          setPost({ id: found.id, ...found.data() } as BlogPost);
        } else {
          setPost(null);
        }
      } catch {
        if (!cancelled) setPost(null);
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [slug]);

  if (loading) {
    return (
      <div className="mx-auto max-w-3xl px-4 py-16 text-sm text-[var(--muted)] sm:px-6 lg:px-8">
        Yükleniyor…
      </div>
    );
  }

  if (!post || post.published === false) {
    return (
      <div className="mx-auto max-w-3xl px-4 py-16 sm:px-6 lg:px-8">
        <p className="text-sm text-[var(--muted)]">Yazı bulunamadı veya yayında değil.</p>
        <Link href="/blog" className="mt-4 inline-flex items-center gap-2 text-sm font-semibold text-[var(--navy)]">
          <ArrowLeft className="h-4 w-4" /> Bloga dön
        </Link>
      </div>
    );
  }

  return (
    <article className="mx-auto max-w-3xl px-4 py-14 sm:px-6 lg:px-8">
      <FadeIn>
        <Link
          href="/blog"
          className="inline-flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-[var(--gold-dark)] hover:text-[var(--navy)]"
        >
          <ArrowLeft className="h-3.5 w-3.5" /> Tüm yazılar
        </Link>
        <h1 className="mt-4 font-[family-name:var(--font-display)] text-4xl font-medium tracking-tight text-[var(--navy)]">
          {post.title}
        </h1>
        <p className="mt-4 text-base leading-relaxed text-[var(--muted)]">{post.excerpt}</p>
      </FadeIn>

      {post.coverImageUrl ? (
        <FadeIn className="mt-10">
          <div className="relative aspect-[16/9] w-full overflow-hidden rounded-2xl border border-black/5 bg-[#f0f2f7] shadow-sm">
            <Image
              src={publicImageSrc(post.coverImageUrl)}
              alt=""
              fill
              className="object-cover"
              priority
              unoptimized
            />
          </div>
        </FadeIn>
      ) : null}

      <FadeIn className="mt-10">
        <div className="mt-10 max-w-none">
          {String(post.content ?? "")
            .split(/\n\n+/)
            .map((para, idx) => (
              <p key={idx} className="mb-4 text-base leading-relaxed text-[var(--muted)] last:mb-0">
                {para}
              </p>
            ))}
        </div>
      </FadeIn>
    </article>
  );
}
