'use client';

import React, { useState } from 'react';

import { useRouter } from 'next/navigation';

import { AnalysisPackageWithVariant } from '@/packages/shared/src/components/select-analysis-package';
import { pathsConfig } from '@/packages/shared/src/config';

import { Spinner } from '@kit/ui/makerkit/spinner';
import { Trans } from '@kit/ui/makerkit/trans';
import { Button } from '@kit/ui/shadcn/button';
import { toast } from '@kit/ui/shadcn/sonner';
import { Table, TableBody, TableCell, TableRow } from '@kit/ui/shadcn/table';

import { handleAddToCart } from '~/lib/services/medusaCart.service';
import { cn } from '~/lib/utils';

const AddToCartButton = ({
  onClick,
  disabled,
  isLoading,
}: {
  onClick: () => void;
  disabled: boolean;
  isLoading: boolean;
}) => {
  return (
    <TableCell align="center" className="xs:px-2 px-1 py-6">
      <Button
        onClick={onClick}
        disabled={disabled}
        className="xs:p-6 xs:text-sm relative p-2 text-[10px]"
      >
        {isLoading && (
          <div className="absolute inset-0 flex items-center justify-center">
            <Spinner />
          </div>
        )}
        <div
          className={cn({
            invisible: isLoading,
          })}
        >
          <Trans i18nKey="compare-packages-modal:selectThisPackage" />
        </div>
      </Button>
    </TableCell>
  );
};

const ComparePackagesAddToCartButtons = ({
  countryCode,
  standardPackage,
  standardPlusPackage,
  premiumPackage,
}: {
  countryCode: string;
  standardPackage: AnalysisPackageWithVariant;
  standardPlusPackage: AnalysisPackageWithVariant;
  premiumPackage: AnalysisPackageWithVariant;
}) => {
  const [addedPackage, setAddedPackage] = useState<string | null>(null);
  const router = useRouter();

  const handleSelect = async ({ variantId }: AnalysisPackageWithVariant) => {
    setAddedPackage(variantId);
    try {
      await handleAddToCart({
        selectedVariant: { id: variantId },
        countryCode,
      });
      setAddedPackage(null);
      toast.success(
        <Trans i18nKey={'order-analysis-package:analysisPackageAddedToCart'} />,
      );
      router.push(pathsConfig.app.cart);
    } catch (e) {
      toast.error(
        <Trans
          i18nKey={'order-analysis-package:analysisPackageAddToCartError'}
        />,
      );
      setAddedPackage(null);
      console.error(e);
    }
  };

  return (
    <Table>
      <TableBody>
        <TableRow>
          <TableCell className="w-[30vw] py-6" />
          <AddToCartButton
            onClick={() => handleSelect(standardPackage)}
            disabled={!!addedPackage}
            isLoading={addedPackage === standardPackage.variantId}
          />
          <AddToCartButton
            onClick={() => handleSelect(standardPlusPackage)}
            disabled={!!addedPackage}
            isLoading={addedPackage === standardPlusPackage.variantId}
          />
          <AddToCartButton
            onClick={() => handleSelect(premiumPackage)}
            disabled={!!addedPackage}
            isLoading={addedPackage === premiumPackage.variantId}
          />
        </TableRow>
      </TableBody>
    </Table>
  );
};

export default ComparePackagesAddToCartButtons;
