import { createContext, useContext, useEffect, useState, ReactNode } from "react";

export interface CartItem {
  id: string;
  caseId: string;
  description: string;
  needType: string;
  requestedAmount: number;
  collectedAmount: number;
  amount: number;
}

interface CartContextType {
  items: CartItem[];
  addItem: (item: Omit<CartItem, "amount">, amount: number) => void;
  removeItem: (id: string) => void;
  updateAmount: (id: string, amount: number) => void;
  isInCart: (id: string) => boolean;
  clear: () => void;
  count: number;
  total: number;
}

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

const STORAGE_KEY = "ehsan-cart";

export function CartProvider({ children }: { children: ReactNode }) {
  const [items, setItems] = useState<CartItem[]>(() => {
    try {
      const saved = localStorage.getItem(STORAGE_KEY);
      if (!saved) return [];
      const parsed = JSON.parse(saved);
      if (!Array.isArray(parsed)) return [];
      return parsed
        .filter((i) => i && typeof i.id === "string")
        .map((i) => ({
          id: String(i.id),
          caseId: String(i.caseId ?? ""),
          description: String(i.description ?? ""),
          needType: String(i.needType ?? ""),
          requestedAmount: Number(i.requestedAmount) || 0,
          collectedAmount: Number(i.collectedAmount) || 0,
          amount: Number(i.amount) || 0,
        }));
    } catch {
      return [];
    }
  });

  useEffect(() => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(items));
  }, [items]);

  const addItem = (item: Omit<CartItem, "amount">, amount: number) => {
    setItems((prev) => {
      if (prev.some((i) => i.id === item.id)) return prev;
      return [...prev, { ...item, amount: amount > 0 ? amount : 0 }];
    });
  };

  const removeItem = (id: string) => {
    setItems((prev) => prev.filter((i) => i.id !== id));
  };

  const updateAmount = (id: string, amount: number) => {
    setItems((prev) =>
      prev.map((i) => (i.id === id ? { ...i, amount: amount > 0 ? amount : 0 } : i))
    );
  };

  const isInCart = (id: string) => items.some((i) => i.id === id);

  const clear = () => setItems([]);

  const count = items.length;
  const total = items.reduce((sum, i) => sum + (i.amount || 0), 0);

  const value: CartContextType = {
    items,
    addItem,
    removeItem,
    updateAmount,
    isInCart,
    clear,
    count,
    total,
  };

  return <CartContext.Provider value={value}>{children}</CartContext.Provider>;
}

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