import React, { createContext, useContext, useState, ReactNode } from 'react';

export interface CompareProduct {
  id: string | number;
  name: string;
  sku: string;
  category: string;
  price: number;
  image: string;
  unitsSold?: number;
  // Admin-specific
  verified?: boolean;
  // User-specific
  closing?: number;
  unit?: string;
  color?: string;
  label?: string;
  // Global Marketing Metrics
  wholesalePrice?: number;
  mrp?: number;
  profitMargin?: number;
  rating?: number;
  globalSales?: number;
  isGlobal?: boolean;
}

interface CompareContextType {
  selectedProducts: CompareProduct[];
  toggleProduct: (product: CompareProduct) => void;
  removeProduct: (id: string | number) => void;
  clearSelection: () => void;
  isComparing: boolean;
  setIsComparing: (val: boolean) => void;
  hideCompareBar: boolean;
  setHideCompareBar: (val: boolean) => void;
}

const CompareContext = createContext<CompareContextType | undefined>(undefined);

export function CompareProvider({ children }: { children: ReactNode }) {
  const [selectedProducts, setSelectedProducts] = useState<CompareProduct[]>([]);
  const [isComparing, setIsComparing] = useState(false);
  const [hideCompareBar, setHideCompareBar] = useState(false);

  const toggleProduct = (product: CompareProduct) => {
    setSelectedProducts((prev) => {
      const exists = prev.find((p) => String(p.id) === String(product.id));
      if (exists) {
        return prev.filter((p) => String(p.id) !== String(product.id));
      }
      if (prev.length >= 5) {
        return prev; // Max 5 items
      }
      return [...prev, product];
    });
  };

  const removeProduct = (id: string | number) => {
    setSelectedProducts((prev) => prev.filter((p) => String(p.id) !== String(id)));
  };

  const clearSelection = () => {
    setSelectedProducts([]);
    setIsComparing(false);
  };

  return (
    <CompareContext.Provider
      value={{
        selectedProducts,
        toggleProduct,
        removeProduct,
        clearSelection,
        isComparing,
        setIsComparing,
        hideCompareBar,
        setHideCompareBar,
      }}
    >
      {children}
    </CompareContext.Provider>
  );
}

export function useCompare() {
  const context = useContext(CompareContext);
  if (!context) {
    throw new Error('useCompare must be used within a CompareProvider');
  }
  return context;
}
