"use client";
import { useState, useEffect, useCallback } from "react";
import { listingService } from "@/services/marketplace/listing.service";
import type { Listing } from "@/types/marketplace";

export function useListing(slug: string) {
  const [listing, setListing] = useState<Listing | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!slug) return;
    setLoading(true);
    setError(null);
    listingService
      .getListing(slug)
      .then(setListing)
      .catch(() => setError("Failed to load listing"))
      .finally(() => setLoading(false));
  }, [slug]);

  const toggleWishlist = useCallback(async () => {
    if (!listing) return;
    const res = await listingService.toggleWishlist(listing.id);
    setListing((prev) =>
      prev
        ? { ...prev, wishlisted: res.wishlisted ? prev.wishlisted + 1 : prev.wishlisted - 1 }
        : null
    );
  }, [listing]);

  return { listing, loading, error, toggleWishlist };
}
