"use client";
import { useState, useCallback } from "react";

const BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL ?? "";

export interface ReviewPayload {
  listingId: string;
  orderId: string;
  rating: number;
  title: string;
  text: string;
}

export interface Review {
  id: string;
  listingId: string;
  rating: number;
  title: string;
  text: string;
  buyerName: string;
  buyerAvatar: string;
  createdAt: string;
  helpful: number;
  verified: boolean;
}

export function useReviews(listingId?: string) {
  const [reviews, setReviews] = useState<Review[]>([]);
  const [loading, setLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const fetchReviews = useCallback(async () => {
    if (!listingId) return;
    setLoading(true);
    try {
      const res = await fetch(`${BASE_URL}/api/marketplace/listings/${listingId}/reviews`);
      setReviews(await res.json());
    } catch {
      setError("Failed to load reviews");
    } finally {
      setLoading(false);
    }
  }, [listingId]);

  const submitReview = useCallback(async (payload: ReviewPayload) => {
    setSubmitting(true);
    setError(null);
    try {
      const res = await fetch(
        `${BASE_URL}/api/marketplace/listings/${payload.listingId}/reviews`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(payload),
        }
      );
      if (!res.ok) throw new Error("Failed to submit review");
      const newReview: Review = await res.json();
      setReviews((prev) => [newReview, ...prev]);
    } catch {
      setError("Could not submit review. Please try again.");
    } finally {
      setSubmitting(false);
    }
  }, []);

  const markHelpful = useCallback(async (reviewId: string) => {
    await fetch(`${BASE_URL}/api/marketplace/reviews/${reviewId}/helpful`, {
      method: "POST",
    });
    setReviews((prev) =>
      prev.map((r) => (r.id === reviewId ? { ...r, helpful: r.helpful + 1 } : r))
    );
  }, []);

  return {
    reviews,
    loading,
    submitting,
    error,
    fetchReviews,
    submitReview,
    markHelpful,
  };
}
