"use client";
import { useState, useCallback } from "react";
import type { Address, CartItem, PaymentMethod, DeliveryType } from "@/types/marketplace";

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

export interface CheckoutState {
  items: CartItem[];
  selectedAddress: Address | null;
  paymentMethod: PaymentMethod | null;
  deliveryType: DeliveryType;
  couponCode: string;
  discount: number;
  step: "address" | "delivery" | "payment" | "review" | "success";
}

export function useCheckout(initialItems: CartItem[] = []) {
  const [state, setState] = useState<CheckoutState>({
    items: initialItems,
    selectedAddress: null,
    paymentMethod: null,
    deliveryType: "standard",
    couponCode: "",
    discount: 0,
    step: "address",
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [orderId, setOrderId] = useState<string | null>(null);

  const setAddress = useCallback((address: Address) => {
    setState((prev) => ({ ...prev, selectedAddress: address }));
  }, []);

  const setPayment = useCallback((method: PaymentMethod) => {
    setState((prev) => ({ ...prev, paymentMethod: method }));
  }, []);

  const setDelivery = useCallback((type: DeliveryType) => {
    setState((prev) => ({ ...prev, deliveryType: type }));
  }, []);

  const applyCoupon = useCallback(async (code: string) => {
    try {
      const res = await fetch(`${BASE_URL}/api/marketplace/coupons/validate`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ code }),
      });
      if (!res.ok) throw new Error("Invalid coupon");
      const { discount } = await res.json();
      setState((prev) => ({ ...prev, couponCode: code, discount }));
    } catch {
      setError("Invalid or expired coupon");
    }
  }, []);

  const placeOrder = useCallback(async () => {
    if (!state.selectedAddress || !state.paymentMethod) return;
    setLoading(true);
    setError(null);
    try {
      const res = await fetch(`${BASE_URL}/api/marketplace/orders`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          items: state.items,
          addressId: state.selectedAddress.id,
          paymentMethod: state.paymentMethod,
          deliveryType: state.deliveryType,
          couponCode: state.couponCode || undefined,
        }),
      });
      if (!res.ok) throw new Error("Failed to place order");
      const { orderId: newOrderId } = await res.json();
      setOrderId(newOrderId);
      setState((prev) => ({ ...prev, step: "success" }));
    } catch {
      setError("Order placement failed. Please try again.");
    } finally {
      setLoading(false);
    }
  }, [state]);

  const goToStep = useCallback((step: CheckoutState["step"]) => {
    setState((prev) => ({ ...prev, step }));
  }, []);

  const subtotal = state.items.reduce((sum, i) => sum + i.price * i.quantity, 0);

  return {
    state,
    loading,
    error,
    orderId,
    subtotal,
    setAddress,
    setPayment,
    setDelivery,
    applyCoupon,
    placeOrder,
    goToStep,
  };
}
