import { useState, useEffect, useCallback } from "react";
import type { Product, CartItem, ProductVariant } from "@/types";

interface CartStore {
  items: CartItem[];
  wishlist: Product[];
  isDrawerOpen: boolean;
  addToCart: (product: Product, quantity?: number, variant?: ProductVariant) => void;
  removeFromCart: (key: string) => void;
  updateQuantity: (key: string, quantity: number) => void;
  clearCart: () => void;
  toggleWishlist: (product: Product) => void;
  isInWishlist: (productId: string) => boolean;
  openDrawer: () => void;
  closeDrawer: () => void;
  totalItems: number;
  totalPrice: number;
}

const CART_KEY = "bnpash_cart";
const WISHLIST_KEY = "bnpash_wishlist";

function loadCart(): CartItem[] {
  try {
    const saved = localStorage.getItem(CART_KEY);
    return saved ? JSON.parse(saved) : [];
  } catch {
    return [];
  }
}

function loadWishlist(): Product[] {
  try {
    const saved = localStorage.getItem(WISHLIST_KEY);
    return saved ? JSON.parse(saved) : [];
  } catch {
    return [];
  }
}

function makeKey(productId: string, variantId?: string) {
  return variantId ? `${productId}__${variantId}` : productId;
}

let globalItems: CartItem[] = loadCart();
let globalWishlist: Product[] = loadWishlist();
let globalDrawerOpen = false;
const listeners: Set<() => void> = new Set();

function notify() {
  listeners.forEach((fn) => fn());
}

export function useCartStore(): CartStore {
  const [, forceUpdate] = useState(0);

  useEffect(() => {
    const update = () => forceUpdate((n) => n + 1);
    listeners.add(update);
    return () => {
      listeners.delete(update);
    };
  }, []);

  const addToCart = useCallback((product: Product, quantity = 1, variant?: ProductVariant) => {
    const key = makeKey(product.id, variant?.id);
    const existing = globalItems.find((i) => i.variantKey === key);
    if (existing) {
      globalItems = globalItems.map((i) =>
        i.variantKey === key ? { ...i, quantity: i.quantity + quantity } : i
      );
    } else {
      globalItems = [...globalItems, { product, quantity, variant, variantKey: key }];
    }
    globalDrawerOpen = true;
    localStorage.setItem(CART_KEY, JSON.stringify(globalItems));
    notify();
  }, []);

  const removeFromCart = useCallback((key: string) => {
    globalItems = globalItems.filter((i) => i.variantKey !== key && i.product.id !== key);
    localStorage.setItem(CART_KEY, JSON.stringify(globalItems));
    notify();
  }, []);

  const updateQuantity = useCallback((key: string, quantity: number) => {
    if (quantity <= 0) {
      globalItems = globalItems.filter((i) => i.variantKey !== key && i.product.id !== key);
    } else {
      globalItems = globalItems.map((i) =>
        (i.variantKey === key || i.product.id === key) ? { ...i, quantity } : i
      );
    }
    localStorage.setItem(CART_KEY, JSON.stringify(globalItems));
    notify();
  }, []);

  const clearCart = useCallback(() => {
    globalItems = [];
    localStorage.setItem(CART_KEY, JSON.stringify(globalItems));
    notify();
  }, []);

  const toggleWishlist = useCallback((product: Product) => {
    const exists = globalWishlist.find((p) => p.id === product.id);
    if (exists) {
      globalWishlist = globalWishlist.filter((p) => p.id !== product.id);
    } else {
      globalWishlist = [...globalWishlist, product];
    }
    localStorage.setItem(WISHLIST_KEY, JSON.stringify(globalWishlist));
    notify();
  }, []);

  const isInWishlist = useCallback((productId: string) => {
    return globalWishlist.some((p) => p.id === productId);
  }, []);

  const openDrawer = useCallback(() => {
    globalDrawerOpen = true;
    notify();
  }, []);

  const closeDrawer = useCallback(() => {
    globalDrawerOpen = false;
    notify();
  }, []);

  const totalItems = globalItems.reduce((sum, i) => sum + i.quantity, 0);
  const totalPrice = globalItems.reduce(
    (sum, i) => sum + (i.variant ? i.variant.price : i.product.price) * i.quantity,
    0
  );

  return {
    items: globalItems,
    wishlist: globalWishlist,
    isDrawerOpen: globalDrawerOpen,
    addToCart,
    removeFromCart,
    updateQuantity,
    clearCart,
    toggleWishlist,
    isInWishlist,
    openDrawer,
    closeDrawer,
    totalItems,
    totalPrice,
  };
}
