"use client";

import { useEffect, useState } from "react";
import { collection, limit, onSnapshot, query, where } from "firebase/firestore";
import { getDb, firebaseConfigured } from "@/lib/firebase";
import { COLLECTIONS } from "@/lib/firestore-paths";
import type { TestimonialSubmission } from "@/types/models";

const FETCH_CAP = 500;

function sortApprovedRows(rows: (TestimonialSubmission & { id: string })[]) {
  return [...rows].sort((a, b) => {
    const oa = typeof a.order === "number" ? a.order : Number.MAX_SAFE_INTEGER;
    const ob = typeof b.order === "number" ? b.order : Number.MAX_SAFE_INTEGER;
    if (oa !== ob) return oa - ob;
    const ta = a.approvedAt?.toMillis?.() ?? a.createdAt?.toMillis?.() ?? 0;
    const tb = b.approvedAt?.toMillis?.() ?? b.createdAt?.toMillis?.() ?? 0;
    return tb - ta;
  });
}

/** Onaylı müvekkil yorumları — ana sayfa ve /bizi-degerlendirin için */
export function useApprovedTestimonials(max = 12) {
  const [items, setItems] = useState<(TestimonialSubmission & { id: string })[]>([]);
  const [loading, setLoading] = useState(firebaseConfigured);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!firebaseConfigured) {
      setItems([]);
      setLoading(false);
      return;
    }
    const db = getDb();
    if (!db) {
      setLoading(false);
      return;
    }
    const q = query(
      collection(db, COLLECTIONS.testimonialSubmissions),
      where("status", "==", "approved"),
      limit(FETCH_CAP)
    );
    setLoading(true);
    const unsub = onSnapshot(
      q,
      (snap) => {
        const rows = snap.docs.map((d) => ({ id: d.id, ...d.data() } as TestimonialSubmission & { id: string }));
        const sorted = sortApprovedRows(rows);
        setItems(sorted.slice(0, max));
        setLoading(false);
        setError(null);
      },
      (e) => {
        console.error(e);
        setError(
          e.code === "failed-precondition"
            ? "Firestore indeksi gerekli: Firebase konsoldaki bağlantıyı kullanın veya `npm run firebase:deploy:rules` ile indeksleri yükleyin."
            : e.code === "permission-denied"
              ? "Yorumları okuma izni yok. Firestore kurallarını kontrol edin."
              : "Yorumlar yüklenemedi."
        );
        setLoading(false);
      }
    );
    return () => unsub();
  }, [max]);

  return { items, loading, error };
}
