import { useState } from 'react';
import { useAddProductToBasket } from './index';
import { pushAddToCart } from '@theme/utils/gtm';
import { validateVariantSelection } from '../utils/variant-validation';
import { VariantType } from '@akinon/next/types';

interface Product {
  pk: number;
  [key: string]: any;
}

interface UseProductCartProps {
  product: Product;
  variants: VariantType[];
}

interface AddToCartError {
  data?: {
    non_field_errors?: string[];
    [key: string]: string[];
  };
}

export const useProductCart = ({ product, variants }: UseProductCartProps) => {
  const [productError, setProductError] = useState<React.ReactNode | null>(
    null
  );
  const [addProduct, { isLoading: isAddToCartLoading }] =
    useAddProductToBasket();

  const formatError = (error: AddToCartError) => {
    if (error?.data?.non_field_errors) {
      return error.data.non_field_errors;
    }

    if (error?.data) {
      return Object.keys(error.data).map(
        (key) => `${key}: ${error.data[key].join(', ')}`
      );
    }

    return 'An error occurred';
  };

  const addProductToCart = async (quantity: number = 1) => {
    const validation = validateVariantSelection(variants);

    if (!validation.isValid) {
      setProductError(validation.errorMessage);
      return false;
    }

    try {
      await addProduct({
        product: product.pk,
        quantity,
        attributes: {}
      });

      pushAddToCart(product);
      setProductError(null);
      return true;
    } catch (error) {
      const formattedError = formatError(error as AddToCartError);
      setProductError(formattedError);
      return false;
    }
  };

  const clearProductError = () => {
    setProductError(null);
  };

  return {
    addProductToCart,
    productError,
    clearProductError,
    isAddToCartLoading
  };
};
