import React from 'react';
import { Trans } from '@akinon/next/components/trans';
import { VariantType } from '@akinon/next/types';

export const isVariantSelectionComplete = (variants: VariantType[]): boolean => {
  return variants?.every((variant) =>
    variant?.options.some((opt) => opt.is_selected)
  );
};

export const getUnselectedVariant = (variants: VariantType[]): VariantType | undefined => {
  return variants.find((variant) =>
    variant.options.every((opt) => !opt.is_selected)
  );
};

export const createVariantErrorMessage = (unselectedVariant: VariantType) => {
  const TransComponent = Trans as any;
  return React.createElement(
    TransComponent,
    {
      i18nKey: "product.please_select_variant",
      components: {
        VariantName: React.createElement('span', {}, unselectedVariant.attribute_name)
      }
    }
  );
};

export const validateVariantSelection = (variants: VariantType[]) => {
  const unselectedVariant = getUnselectedVariant(variants);
  
  if (unselectedVariant) {
    return {
      isValid: false,
      errorMessage: createVariantErrorMessage(unselectedVariant)
    };
  }

  return { isValid: true, errorMessage: null };
};