import React from 'react';
import clsx from 'clsx';
import { Button, Icon, Modal } from '@theme/components';
import { useLocalization, useToast } from '@akinon/next/hooks';
import PluginModule, { Component } from '@akinon/next/components/plugin-module';
import { formatErrorMessage } from '@akinon/next/utils/format-error-message';
import { validateVariantSelection } from '../../utils/variant-validation';
import { VariantType } from '@akinon/next/types';

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

interface ProductActionsProps {
  product: Product;
  variants: VariantType[];
  inStock: boolean;
  isVariantLoading: boolean;
  onAddToCart: () => void;
  onAddToStockAlert: () => void;
  onClearError: () => void;
  isAddToCartLoading: boolean;
  isAddToStockAlertLoading: boolean;
  productError: React.ReactNode | null;
  isModalOpen: boolean;
  stockAlertResponseMessage: React.ReactNode | null;
  onCloseModal: () => void;
}

export const ProductActions: React.FC<ProductActionsProps> = ({
  product,
  variants,
  inStock,
  isVariantLoading,
  onAddToCart,
  onAddToStockAlert,
  onClearError,
  isAddToCartLoading,
  isAddToStockAlertLoading,
  productError,
  isModalOpen,
  stockAlertResponseMessage,
  onCloseModal
}) => {
  const { t } = useLocalization();
  const { error: showError } = useToast();

  const checkoutProviderProps = {
    product,
    clearBasket: true,
    addBeforeClick: () => validateVariantSelection(variants).isValid,
    openMiniBasket: false,
    className: clsx([
      'py-2.5',
      'bg-black',
      'relative',
      'hover:bg-black',
      'before:content-[""]',
      'before:w-6',
      'before:h-6',
      'before:bg-white',
      'before:absolute',
      'before:rounded-r-[18px]',
      'before:left-0',
      'after:content-[""]',
      'after:absolute',
      'after:w-3',
      'after:h-3',
      'after:bg-[#d02c2f]',
      'after:rounded-xl',
      'after:left-1'
    ]),
    onError: (error: any) => {
      const formattedError = error?.data?.non_field_errors ||
        Object.keys(error?.data || {}).map(
          (key) => `${key}: ${error?.data[key].join(', ')}`
        );
      showError(formatErrorMessage(formattedError));
    }
  };

  const handleMainActionClick = () => {
    onClearError();
    
    if (inStock) {
      onAddToCart();
    } else {
      onAddToStockAlert();
    }
  };

  return (
    <>
      {productError && (
        <div className="mt-4 text-xs text-center text-error">
          {productError}
        </div>
      )}

      <Button
        disabled={isAddToCartLoading || isAddToStockAlertLoading || isVariantLoading}
        className={clsx(
          'fixed bottom-0 right-0 w-1/2 h-14 z-[20] flex items-center justify-center fill-primary-foreground',
          'hover:fill-primary sm:relative sm:w-full sm:mt-3 sm:font-semibold sm:h-12'
        )}
        onClick={handleMainActionClick}
        data-testid="product-add-to-cart"
      >
        {isVariantLoading ? (
          <Icon
            name="spinner"
            size={20}
            className="animate-spin mr-4 fill-primary"
          />
        ) : inStock ? (
          <span>{t('product.add_to_cart')}</span>
        ) : (
          <>
            <Icon name="bell" size={20} className="mr-4" />
            <span>{t('product.add_stock_alert')}</span>
          </>
        )}
      </Button>

      <PluginModule
        component={Component.AkifastCheckoutButton}
        props={{
          ...checkoutProviderProps,
          isPdp: true
        }}
      />

      <PluginModule
        component={Component.OneClickCheckoutButtons}
        props={checkoutProviderProps}
      />

      <Modal
        portalId="stock-alert-modal"
        open={isModalOpen}
        setOpen={onCloseModal}
        showCloseButton={false}
        className="w-5/6 md:max-w-md"
      >
        <div className="flex flex-col items-center justify-center gap-4 px-6 py-9">
          <Icon name="bell" size={48} />
          <h2 className="text-xl font-semibold">
            {t('product.stock_alert.title')}
          </h2>
          <div className="max-w-40 text-xs text-center leading-4">
            <p>{stockAlertResponseMessage}</p>
          </div>
          <Button
            onClick={onCloseModal}
            appearance="outlined"
            className="font-semibold px-10 h-12"
          >
            {t('product.stock_alert.close_button')}
          </Button>
        </div>
      </Modal>
    </>
  );
};