"use client";

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

export interface CartItem {
  product: Product;
  quantity: number;
}

export interface Coupon {
  code: string;
  discountPercent?: number;
  discountAmount?: number;
  minSpend?: number;
}

export const VALID_COUPONS: Record<string, Coupon> = {
  BIENVENIDO10: { code: "BIENVENIDO10", discountPercent: 10, minSpend: 25 },
  PANETTONE5: { code: "PANETTONE5", discountAmount: 5, minSpend: 30 },
  ASENCIO1758: { code: "ASENCIO1758", discountPercent: 15, minSpend: 50 },
};

interface CartContextType {
  cart: CartItem[];
  addToCart: (product: Product, quantity?: number) => void;
  removeFromCart: (productId: string) => void;
  updateQuantity: (productId: string, quantity: number) => void;
  clearCart: () => void;
  totalItems: number;
  subtotal: number;
  shippingCost: number;
  discount: number;
  total: number;
  hasFreeShipping: boolean;
  amountNeededForFreeShipping: number;
  isCartOpen: boolean;
  setIsCartOpen: (open: boolean) => void;
  appliedCoupon: Coupon | null;
  applyCoupon: (code: string) => { success: boolean; message: string };
  removeCoupon: () => void;
}

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

export function CartProvider({ children }: { children: React.ReactNode }) {
  const [cart, setCart] = useState<CartItem[]>([]);
  const [isCartOpen, setIsCartOpen] = useState(false);
  const [appliedCoupon, setAppliedCoupon] = useState<Coupon | null>(null);
  const [mounted, setMounted] = useState(false);

  // Load from localStorage on client
  useEffect(() => {
    try {
      const raw = localStorage.getItem("rs_cart") || localStorage.getItem("raul_asencio_cart");
      if (raw) {
        const parsed = JSON.parse(raw);
        if (Array.isArray(parsed)) {
          const normalized: CartItem[] = parsed.map((item: any) => {
            if (item.product) {
              return { product: item.product, quantity: item.quantity || 1 };
            }
            return {
              product: {
                id: String(item.id),
                name: item.name,
                slug: item.slug || "",
                price: Number(item.price),
                category: item.category || "Panettones",
                allCategories: item.allCategories || [item.category || "Panettones"],
                inStock: true,
                images: item.images || [item.thumbnail],
                thumbnail: item.thumbnail,
                weight: item.weight || "",
                shortDescription: item.shortDescription || "",
                description: item.description || "",
                badges: item.badges || [],
                isFreeShipping: item.isFreeShipping ?? (item.category === "Panettones"),
                rating: item.rating || 5,
                reviewsCount: item.reviewsCount || 10,
                ingredients: item.ingredients || "",
                allergens: item.allergens || [],
                conservation: item.conservation || "",
              },
              quantity: item.quantity || 1,
            };
          });
          setCart(normalized);
        }
      }
      const savedCoupon = localStorage.getItem("rs_coupon") || localStorage.getItem("raul_asencio_coupon");
      if (savedCoupon) {
        setAppliedCoupon(JSON.parse(savedCoupon));
      }
    } catch (e) {
      console.error("Error reading cart from localStorage", e);
    }
    setMounted(true);
  }, []);

  // Save to localStorage (dual write to rs_cart and raul_asencio_cart for 100% interoperability)
  useEffect(() => {
    if (!mounted) return;
    try {
      const serialized = JSON.stringify(cart);
      localStorage.setItem("raul_asencio_cart", serialized);
      
      // Also save flat version for raulasencio.js
      const flatCart = cart.map(item => ({
        id: item.product.id,
        name: item.product.name,
        price: item.product.price,
        weight: item.product.weight,
        thumbnail: item.product.thumbnail,
        quantity: item.quantity,
        product: item.product
      }));
      localStorage.setItem("rs_cart", JSON.stringify(flatCart));

      if (appliedCoupon) {
        const cJson = JSON.stringify(appliedCoupon);
        localStorage.setItem("raul_asencio_coupon", cJson);
        localStorage.setItem("rs_coupon", cJson);
      } else {
        localStorage.removeItem("raul_asencio_coupon");
        localStorage.removeItem("rs_coupon");
      }
    } catch (e) {
      console.error("Error saving cart to localStorage", e);
    }
  }, [cart, appliedCoupon, mounted]);

  const addToCart = (product: Product, quantity = 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
        );
      }
      return [...prev, { product, quantity }];
    });
    setIsCartOpen(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([]);
    setAppliedCoupon(null);
  };

  const totalItems = cart.reduce((acc, item) => acc + item.quantity, 0);
  const subtotal = cart.reduce(
    (acc, item) => acc + item.product.price * item.quantity,
    0
  );

  // Free shipping rule: Any panettone in cart OR subtotal >= 50€
  const hasPanettone = cart.some((item) => item.product.isFreeShipping);
  const hasFreeShipping = hasPanettone || subtotal >= 50;
  const shippingCost = cart.length === 0 ? 0 : hasFreeShipping ? 0 : 5.95;
  const amountNeededForFreeShipping = hasFreeShipping
    ? 0
    : Math.max(0, 50 - subtotal);

  // Calculate discount
  let discount = 0;
  if (appliedCoupon) {
    if (appliedCoupon.discountPercent) {
      discount = (subtotal * appliedCoupon.discountPercent) / 100;
    } else if (appliedCoupon.discountAmount) {
      discount = Math.min(subtotal, appliedCoupon.discountAmount);
    }
  }

  const total = Math.max(0, subtotal - discount + shippingCost);

  const applyCoupon = (code: string) => {
    const cleanCode = code.trim().toUpperCase();
    const coupon = VALID_COUPONS[cleanCode];

    if (!coupon) {
      return { success: false, message: "Código de cupón no válido." };
    }

    if (coupon.minSpend && subtotal < coupon.minSpend) {
      return {
        success: false,
        message: `Este cupón requiere un pedido mínimo de ${coupon.minSpend.toFixed(2)}€.`,
      };
    }

    setAppliedCoupon(coupon);
    return {
      success: true,
      message: `¡Cupón ${coupon.code} aplicado correctamente!`,
    };
  };

  const removeCoupon = () => {
    setAppliedCoupon(null);
  };

  return (
    <CartContext.Provider
      value={{
        cart,
        addToCart,
        removeFromCart,
        updateQuantity,
        clearCart,
        totalItems,
        subtotal,
        shippingCost,
        discount,
        total,
        hasFreeShipping,
        amountNeededForFreeShipping,
        isCartOpen,
        setIsCartOpen,
        appliedCoupon,
        applyCoupon,
        removeCoupon,
      }}
    >
      {children}
    </CartContext.Provider>
  );
}

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