'use client';

import { IPartial } from '@websolutespa/bom-core';
import { createGenericContext } from '@websolutespa/bom-mixer-hooks';
import React from 'react';
import { IVariants, defaultVariants } from './types';

export type IVariantsContext = Partial<IVariants>;

const [useVariants_, VariantsContextProvider] = createGenericContext<IVariantsContext>(defaultVariants);

export function VariantsProvider({ children, variants }: { children?: React.ReactNode, variants: IPartial<IVariants> }) {
  // console.log('VariantsProvider.context', context);
  const value = { ...defaultVariants };
  Object.entries(variants).forEach(([k, v]) => {
    value[k as keyof IVariants] = { ...value[k as keyof IVariants], ...v } as any;
  });
  /*
  const value: IVariants = { ...defaultVariants };
  */
  /*
  for (const [k, v] of Object.entries(value)) {
    value[k as keyof IVariants] = {...v};
  }
  */
  /*
  Object.entries(variants).forEach(([k, v]) => {
    Object.assign(value[k as keyof IVariants], v);
  });
  */
  return (
    <VariantsContextProvider value={value}>
      {children}
    </VariantsContextProvider>
  );
}

/*
!!! todo: variants deepMerge optimization
*/

export function useVariants<T extends keyof IVariants>(variantKey: T, defaultVariant?: IVariants[T]): IVariants[T] | undefined {
  const customVariants = useVariants_();
  if (customVariants) {
    const customVariant = customVariants[variantKey] as IVariants[T];
    const modifiedVariant: IVariants[T] = { ...defaultVariant, ...customVariant };
    return modifiedVariant;
  } else {
    return defaultVariant;
  }
}

