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

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

export interface TrackingEvent {
  id: string;
  status: string;
  description: string;
  location?: string;
  timestamp: string;
}

export interface TrackingInfo {
  orderId: string;
  trackingId?: string;
  carrier?: string;
  estimatedDelivery: string;
  currentStatus: string;
  events: TrackingEvent[];
}

export function useTracking(orderId: string) {
  const [tracking, setTracking] = useState<TrackingInfo | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchTracking = useCallback(async () => {
    if (!orderId) return;
    setLoading(true);
    setError(null);
    try {
      const res = await fetch(`${BASE_URL}/api/marketplace/orders/${orderId}/tracking`);
      if (!res.ok) throw new Error("Tracking info not available");
      setTracking(await res.json());
    } catch {
      setError("Unable to load tracking information");
    } finally {
      setLoading(false);
    }
  }, [orderId]);

  useEffect(() => {
    fetchTracking();
  }, [fetchTracking]);

  return { tracking, loading, error, refresh: fetchTracking };
}
