'use client';

import { useState } from 'react';

import Image from 'next/image';
import { useRouter } from 'next/navigation';

import { StoreProduct } from '@medusajs/types';
import { Button } from '@medusajs/ui';
import { useTranslation } from 'react-i18next';
import { handleAddToCart } from '../../../../lib/services/medusaCart.service';
import { toast } from '@kit/ui/sonner';

import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
} from '@kit/ui/card';
import { Trans } from '@kit/ui/trans';
import { ButtonTooltip } from './ui/button-tooltip';
import { PackageHeader } from './package-header';

export type AnalysisPackageWithVariant = Pick<StoreProduct, 'title' | 'description' | 'subtitle' | 'metadata'> & {
  variantId: string;
  nrOfAnalyses: number;
  price: number;
  isStandard: boolean;
  isStandardPlus: boolean;
  isPremium: boolean;
};

export default function SelectAnalysisPackage({
  analysisPackage,
  countryCode,
}: {
  analysisPackage: AnalysisPackageWithVariant;
  countryCode: string,
}) {
  const router = useRouter();
  const {
    t,
    i18n: { language },
  } = useTranslation();

  const [isAddingToCart, setIsAddingToCart] = useState(false);
  
  const { nrOfAnalyses, variantId, title, subtitle = '', description = '', price } = analysisPackage;

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

  return (
    <Card key={title}>
      <CardHeader className="relative">
        {description && (
          <ButtonTooltip
            content={description}
            className="absolute top-5 right-5 z-10"
          />
        )}
        <Image
          src="/assets/card-image.png"
          alt="background"
          width={326}
          height={195}
          className="max-h-48 w-full opacity-10"
        />
      </CardHeader>
      <CardContent className="space-y-1 text-center">
        <PackageHeader
          title={title}
          tagColor='bg-cyan'
          analysesNr={t('product:nrOfAnalyses', { nr: nrOfAnalyses })}
          language={language}
          price={price}
        />
        <CardDescription>{subtitle}</CardDescription>
      </CardContent>
      <CardFooter>
        <Button className="w-full text-[10px] sm:text-sm" onClick={handleSelect} isLoading={isAddingToCart}>
          {!isAddingToCart && <Trans i18nKey='order-analysis-package:selectThisPackage' />}
        </Button>
      </CardFooter>
    </Card>
  );
}
