"use client";

import React, { createContext, useContext, useState, useEffect } from "react";
import { Product, CartItem } from "@/types";

interface CartContextType {
  cart: CartItem[];
  wishlist: Product[];
  isCartOpen: boolean;
  setIsCartOpen: (open: boolean) => void;
  isCheckoutOpen: boolean;
  setIsCheckoutOpen: (open: boolean) => void;
  isTrackerOpen: boolean;
  setIsTrackerOpen: (open: boolean) => void;
  isQuoteModalOpen: boolean;
  setIsQuoteModalOpen: (open: boolean) => void;
  activeProductModal: Product | null;
  openProductModal: (product: Product) => void;
  closeProductModal: () => void;
  addToCart: (product: Product, quantity?: number) => void;
  removeFromCart: (productId: string) => void;
  updateQuantity: (productId: string, quantity: number) => void;
  clearCart: () => void;
  toggleWishlist: (product: Product) => void;
  isInWishlist: (productId: string) => boolean;
  appliedPromo: { code: string; discountPercent: number; fixedAmount: number } | null;
  applyPromoCode: (code: string) => { success: boolean; message: string };
  removePromoCode: () => void;
  subtotal: number;
  discountAmount: number;
  vatAmount: number;
  freeShippingThreshold: number;
  amountNeededForFreeShipping: number;
  totalCartItemsCount: number;
  buyNow: (product: Product, quantity?: number) => void;
  recentlyViewed: Product[];
}

const CartContext = createContext<CartContextType | undefined>(undefined);

const FREE_SHIPPING_LIMIT = 750; // R750 for Free SA Delivery

export const CartProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [cart, setCart] = useState<CartItem[]>([]);
  const [wishlist, setWishlist] = useState<Product[]>([]);
  const [recentlyViewed, setRecentlyViewed] = useState<Product[]>([]);
  const [isCartOpen, setIsCartOpen] = useState<boolean>(false);
  const [isCheckoutOpen, setIsCheckoutOpen] = useState<boolean>(false);
  const [isTrackerOpen, setIsTrackerOpen] = useState<boolean>(false);
  const [isQuoteModalOpen, setIsQuoteModalOpen] = useState<boolean>(false);
  const [activeProductModal, setActiveProductModal] = useState<Product | null>(null);
  const [appliedPromo, setAppliedPromo] = useState<{
    code: string;
    discountPercent: number;
    fixedAmount: number;
  } | null>(null);

  // Load saved state from localStorage
  useEffect(() => {
    try {
      const savedCart = localStorage.getItem("ds_cart");
      if (savedCart) setCart(JSON.parse(savedCart));

      const savedWishlist = localStorage.getItem("ds_wishlist");
      if (savedWishlist) setWishlist(JSON.parse(savedWishlist));

      const savedRecent = localStorage.getItem("ds_recent");
      if (savedRecent) setRecentlyViewed(JSON.parse(savedRecent));
    } catch (e) {
      console.error("Error loading cart from storage", e);
    }
  }, []);

  // Save to localStorage on change
  useEffect(() => {
    try {
      localStorage.setItem("ds_cart", JSON.stringify(cart));
    } catch (e) {}
  }, [cart]);

  useEffect(() => {
    try {
      localStorage.setItem("ds_wishlist", JSON.stringify(wishlist));
    } catch (e) {}
  }, [wishlist]);

  useEffect(() => {
    try {
      localStorage.setItem("ds_recent", JSON.stringify(recentlyViewed));
    } catch (e) {}
  }, [recentlyViewed]);

  const addToCart = (product: Product, quantity: number = 1) => {
    setCart((prev) => {
      const existing = prev.find((item) => item.product.id === product.id);
      if (existing) {
        return prev.map((item) =>
          item.product.id === product.id
            ? { ...item, quantity: item.quantity + quantity }
            : item
        );
      } else {
        return [...prev, { product, quantity }];
      }
    });
    setIsCartOpen(true);
  };

  const buyNow = (product: Product, quantity: number = 1) => {
    addToCart(product, quantity);
    setIsCartOpen(false);
    setIsCheckoutOpen(true);
  };

  const removeFromCart = (productId: string) => {
    setCart((prev) => prev.filter((item) => item.product.id !== productId));
  };

  const updateQuantity = (productId: string, quantity: number) => {
    if (quantity <= 0) {
      removeFromCart(productId);
      return;
    }
    setCart((prev) =>
      prev.map((item) =>
        item.product.id === productId ? { ...item, quantity } : item
      )
    );
  };

  const clearCart = () => {
    setCart([]);
    setAppliedPromo(null);
  };

  const toggleWishlist = (product: Product) => {
    setWishlist((prev) => {
      const exists = prev.some((p) => p.id === product.id);
      if (exists) {
        return prev.filter((p) => p.id !== product.id);
      } else {
        return [...prev, product];
      }
    });
  };

  const isInWishlist = (productId: string) => {
    return wishlist.some((p) => p.id === productId);
  };

  const openProductModal = (product: Product) => {
    setActiveProductModal(product);
    // Add to recently viewed
    setRecentlyViewed((prev) => {
      const filtered = prev.filter((p) => p.id !== product.id);
      return [product, ...filtered].slice(0, 8);
    });
  };

  const closeProductModal = () => {
    setActiveProductModal(null);
  };

  const applyPromoCode = (code: string) => {
    const cleanCode = code.trim().toUpperCase();
    if (cleanCode === "DIVERSE10") {
      setAppliedPromo({ code: "DIVERSE10", discountPercent: 10, fixedAmount: 0 });
      return { success: true, message: "10% Discount applied!" };
    } else if (cleanCode === "BACK2SCHOOL") {
      setAppliedPromo({ code: "BACK2SCHOOL", discountPercent: 0, fixedAmount: 50 });
      return { success: true, message: "R50 Off applied to order!" };
    } else if (cleanCode === "FREE99") {
      setAppliedPromo({ code: "FREE99", discountPercent: 15, fixedAmount: 0 });
      return { success: true, message: "15% Special Offer applied!" };
    }
    return { success: false, message: "Invalid promo code. Try DIVERSE10" };
  };

  const removePromoCode = () => {
    setAppliedPromo(null);
  };

  // Subtotal calculation
  const subtotal = cart.reduce((sum, item) => {
    const price = typeof item.product.price === "number" ? item.product.price : parseFloat(item.product.price);
    return sum + price * item.quantity;
  }, 0);

  // Discount calculation
  let discountAmount = 0;
  if (appliedPromo) {
    if (appliedPromo.discountPercent > 0) {
      discountAmount = (subtotal * appliedPromo.discountPercent) / 100;
    } else if (appliedPromo.fixedAmount > 0) {
      discountAmount = Math.min(subtotal, appliedPromo.fixedAmount);
    }
  }

  // SA 15% VAT calculation (included in pricing)
  const vatAmount = (subtotal - discountAmount) * 0.15;

  const totalCartItemsCount = cart.reduce((count, item) => count + item.quantity, 0);

  const amountNeededForFreeShipping = Math.max(0, FREE_SHIPPING_LIMIT - subtotal);

  return (
    <CartContext.Provider
      value={{
        cart,
        wishlist,
        isCartOpen,
        setIsCartOpen,
        isCheckoutOpen,
        setIsCheckoutOpen,
        isTrackerOpen,
        setIsTrackerOpen,
        isQuoteModalOpen,
        setIsQuoteModalOpen,
        activeProductModal,
        openProductModal,
        closeProductModal,
        addToCart,
        removeFromCart,
        updateQuantity,
        clearCart,
        toggleWishlist,
        isInWishlist,
        appliedPromo,
        applyPromoCode,
        removePromoCode,
        subtotal,
        discountAmount,
        vatAmount,
        freeShippingThreshold: FREE_SHIPPING_LIMIT,
        amountNeededForFreeShipping,
        totalCartItemsCount,
        buyNow,
        recentlyViewed,
      }}
    >
      {children}
    </CartContext.Provider>
  );
};

export const useCart = () => {
  const context = useContext(CartContext);
  if (!context) throw new Error("useCart must be used within a CartProvider");
  return context;
};
