'use client';

import { useState, useEffect, useCallback } from 'react';

export interface ResellerCartItem {
  product_id: number;
  name: string;
  sku: string;
  quantity: number;
  wholesale_price: number; // reseller cost price
  price: number;           // retail sell price (editable)
  image: string;
}

const STORAGE_KEY = 'reseller_cart';

function readFromStorage(): ResellerCartItem[] {
  if (typeof window === 'undefined') return [];
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    return raw ? JSON.parse(raw) : [];
  } catch {
    return [];
  }
}

function writeToStorage(cart: ResellerCartItem[]) {
  if (typeof window === 'undefined') return;
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(cart));
  } catch {
    // ignore quota errors silently
  }
}

export function useResellerCart() {
  const [cart, setCartState] = useState<ResellerCartItem[]>([]);
  const [isHydrated, setIsHydrated] = useState(false);

  // Load from localStorage on mount
  useEffect(() => {
    setCartState(readFromStorage());
    setIsHydrated(true);
  }, []);

  // Persist to localStorage on every change only after hydration completes
  useEffect(() => {
    if (isHydrated) {
      writeToStorage(cart);
    }
  }, [cart, isHydrated]);

  // Sync across tabs / windows
  useEffect(() => {
    const onStorage = (e: StorageEvent) => {
      if (e.key === STORAGE_KEY) {
        setCartState(readFromStorage());
      }
    };
    window.addEventListener('storage', onStorage);
    return () => window.removeEventListener('storage', onStorage);
  }, []);

  const addItem = useCallback((product: {
    id?: number;
    product_id?: number;
    name: string;
    sku?: string;
    reseller_price?: number;
    wholesale_price?: number;
    retail_price?: number;
    price?: number;
    media?: { original_url: string }[];
    image?: string;
    quantity?: number;
  }) => {
    const productId = product.id ?? product.product_id ?? 0;
    const wholesalePrice = product.reseller_price ?? product.wholesale_price ?? 0;
    const retailPrice = Number(product.retail_price ?? product.price ?? wholesalePrice);
    const image = product.media?.[0]?.original_url ?? product.image ?? '/placeholder.png';
    const sku = product.sku ?? 'GENERIC';
    const qty = product.quantity ?? 1;

    setCartState(prev => {
      const existing = prev.find(i => i.product_id === productId);
      if (existing) {
        return prev.map(i =>
          i.product_id === productId
            ? { ...i, quantity: i.quantity + qty }
            : i
        );
      }
      return [...prev, {
        product_id: productId,
        name: product.name,
        sku,
        quantity: qty,
        wholesale_price: wholesalePrice,
        price: retailPrice,
        image,
      }];
    });
  }, []);

  const removeItem = useCallback((productId: number) => {
    setCartState(prev => prev.filter(i => i.product_id !== productId));
  }, []);

  const updateQty = useCallback((productId: number, qty: number) => {
    if (qty <= 0) {
      setCartState(prev => prev.filter(i => i.product_id !== productId));
    } else {
      setCartState(prev =>
        prev.map(i => i.product_id === productId ? { ...i, quantity: qty } : i)
      );
    }
  }, []);

  const updatePrice = useCallback((productId: number, price: number) => {
    setCartState(prev =>
      prev.map(i => i.product_id === productId ? { ...i, price } : i)
    );
  }, []);

  const clearCart = useCallback(() => {
    setCartState([]);
  }, []);

  const cartCount = cart.reduce((acc, i) => acc + i.quantity, 0);
  const subtotal = cart.reduce((acc, i) => acc + i.wholesale_price * i.quantity, 0);
  const totalRetail = cart.reduce((acc, i) => acc + i.price * i.quantity, 0);
  const totalProfit = totalRetail - subtotal;

  return {
    cart,
    addItem,
    removeItem,
    updateQty,
    updatePrice,
    clearCart,
    cartCount,
    subtotal,
    totalRetail,
    totalProfit,
  };
}
