import { useState, useCallback } from 'react';

interface Product {
  id: string;
  name: string;
  price: number;
  stock: number;
  category: string;
  status: 'active' | 'inactive';
}

interface ProductState {
  products: Product[];
  loading: boolean;
  error: string | null;
  currentProduct: Product | null;
  pagination: {
    current: number;
    pageSize: number;
    total: number;
  };
}

const useProductModel = () => {
  const [state, setState] = useState<ProductState>({
    products: [],
    loading: false,
    error: null,
    currentProduct: null,
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0,
    },
  });

  const setProducts = useCallback((products: Product[]) => {
    setState(prev => ({ ...prev, products }));
  }, []);

  const setLoading = useCallback((loading: boolean) => {
    setState(prev => ({ ...prev, loading }));
  }, []);

  const setError = useCallback((error: string | null) => {
    setState(prev => ({ ...prev, error }));
  }, []);

  const setCurrentProduct = useCallback((product: Product | null) => {
    setState(prev => ({ ...prev, currentProduct: product }));
  }, []);

  const setPagination = useCallback((pagination: ProductState['pagination']) => {
    setState(prev => ({ ...prev, pagination }));
  }, []);

  const updateProduct = useCallback((updatedProduct: Product) => {
    setState(prev => ({
      ...prev,
      products: prev.products.map(product => 
        product.id === updatedProduct.id ? updatedProduct : product
      ),
      currentProduct: prev.currentProduct?.id === updatedProduct.id 
        ? updatedProduct 
        : prev.currentProduct,
    }));
  }, []);

  const addProduct = useCallback((newProduct: Product) => {
    setState(prev => ({
      ...prev,
      products: [newProduct, ...prev.products],
      pagination: {
        ...prev.pagination,
        total: prev.pagination.total + 1,
      },
    }));
  }, []);

  const deleteProduct = useCallback((productId: string) => {
    setState(prev => ({
      ...prev,
      products: prev.products.filter(product => product.id !== productId),
      pagination: {
        ...prev.pagination,
        total: prev.pagination.total - 1,
      },
    }));
  }, []);

  return {
    ...state,
    setProducts,
    setLoading,
    setError,
    setCurrentProduct,
    setPagination,
    updateProduct,
    addProduct,
    deleteProduct,
  };
};

export default useProductModel;