import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
import type { CartItem, Product, Coupon } from '../types';
import { api } from '../services/api';
import { useToast } from './ToastContext';

interface CartContextType {
  items: CartItem[];
  itemCount: number;
  subtotal: number;
  discountAmount: number;
  couponCode: string;
  appliedCoupon: Coupon | null;
  finalTotal: number;
  isCartOpen: boolean;
  setIsCartOpen: (open: boolean) => void;
  addToCart: (product: Product, quantity?: number, selectedRegion?: string) => void;
  removeFromCart: (productId: string) => void;
  updateQuantity: (productId: string, quantity: number) => void;
  clearCart: () => void;
  applyCoupon: (code: string) => Promise<boolean>;
  removeCoupon: () => void;
  couponLoading: boolean;
}

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

export const CartProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [items, setItems] = useState<CartItem[]>(() => {
    try {
      const saved = localStorage.getItem('zanashop_cart');
      return saved ? JSON.parse(saved) : [];
    } catch {
      return [];
    }
  });

  const [isCartOpen, setIsCartOpen] = useState(false);
  const [couponCode, setCouponCode] = useState('');
  const [appliedCoupon, setAppliedCoupon] = useState<Coupon | null>(null);
  const [discountAmount, setDiscountAmount] = useState(0);
  const [couponLoading, setCouponLoading] = useState(false);
  const { success, error, info } = useToast();

  // Save cart changes
  useEffect(() => {
    try {
      localStorage.setItem('zanashop_cart', JSON.stringify(items));
    } catch (e) {
      console.error('Failed to save cart:', e);
    }
  }, [items]);

  // Calculate subtotal
  const subtotal = items.reduce((acc, item) => acc + (item.product.price * item.quantity), 0);
  const itemCount = items.reduce((acc, item) => acc + item.quantity, 0);

  // Recalculate coupon discount if cart changes
  useEffect(() => {
    if (!appliedCoupon || items.length === 0) {
      setDiscountAmount(0);
      return;
    }

    if (subtotal < appliedCoupon.minPurchase) {
      setDiscountAmount(0);
      setAppliedCoupon(null);
      setCouponCode('');
      info(`کد تخفیف به دلیل کاهش مبلغ کل به زیر حداقل خرید (${appliedCoupon.minPurchase.toLocaleString('fa-IR')} تومان) حذف شد`);
      return;
    }

    let disc = 0;
    if (appliedCoupon.discountType === 'percent') {
      disc = Math.round((subtotal * appliedCoupon.discountValue) / 100);
      if (appliedCoupon.maxDiscount && disc > appliedCoupon.maxDiscount) {
        disc = appliedCoupon.maxDiscount;
      }
    } else {
      disc = appliedCoupon.discountValue;
    }

    if (disc > subtotal) disc = subtotal;
    setDiscountAmount(disc);
  }, [subtotal, appliedCoupon, items.length, info]);

  const finalTotal = Math.max(0, subtotal - discountAmount);

  const addToCart = (product: Product, quantity = 1, selectedRegion?: string) => {
    if (!product.inStock) {
      error(`محصول "${product.title}" موجود نیست`, 'عدم موجودی');
      return;
    }

    setItems(prev => {
      const idx = prev.findIndex(item => item.product.id === product.id && item.selectedRegion === selectedRegion);
      if (idx > -1) {
        const next = [...prev];
        const newQty = next[idx].quantity + quantity;
        next[idx] = { ...next[idx], quantity: newQty };
        return next;
      } else {
        return [...prev, { product, quantity, selectedRegion }];
      }
    });

    success(`"${product.title}" به سبد خرید اضافه شد`, 'افزودن به سبد');
  };

  const removeFromCart = (productId: string) => {
    setItems(prev => {
      const item = prev.find(i => i.product.id === productId);
      if (item) {
        info(`"${item.product.title}" از سبد خرید حذف شد`);
      }
      return prev.filter(i => i.product.id !== productId);
    });
  };

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

  const clearCart = useCallback(() => {
    setItems([]);
    setAppliedCoupon(null);
    setCouponCode('');
    setDiscountAmount(0);
  }, []);

  const applyCoupon = async (code: string): Promise<boolean> => {
    if (!code || !code.trim()) {
      error('لطفاً کد تخفیف را وارد کنید');
      return false;
    }
    if (items.length === 0) {
      error('سبد خرید شما خالی است');
      return false;
    }

    setCouponLoading(true);
    try {
      const res = await api.validateCoupon(code.trim(), subtotal);
      if (res.valid && res.coupon) {
        setAppliedCoupon(res.coupon);
        setCouponCode(res.coupon.code);
        setDiscountAmount(res.discount);
        success(res.message, 'کد تخفیف اعمال شد');
        return true;
      } else {
        error(res.message || 'کد تخفیف نامعتبر است', 'خطا در اعمال کد');
        return false;
      }
    } catch (err: any) {
      error(err.message || 'خطا در اعتبارسنجی کد تخفیف');
      return false;
    } finally {
      setCouponLoading(false);
    }
  };

  const removeCoupon = () => {
    setAppliedCoupon(null);
    setCouponCode('');
    setDiscountAmount(0);
    info('کد تخفیف حذف شد');
  };

  return (
    <CartContext.Provider
      value={{
        items,
        itemCount,
        subtotal,
        discountAmount,
        couponCode,
        appliedCoupon,
        finalTotal,
        isCartOpen,
        setIsCartOpen,
        addToCart,
        removeFromCart,
        updateQuantity,
        clearCart,
        applyCoupon,
        removeCoupon,
        couponLoading,
      }}
    >
      {children}
    </CartContext.Provider>
  );
};

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