"use client";

import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import Image from 'next/image';
import { useRouter } from 'next/navigation';

import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
} from '@kit/ui/card';
import { Trans } from '@kit/ui/trans';
import { StoreProduct, StoreProductVariant } from '@medusajs/types';
import { Button } from '@medusajs/ui';
import { handleAddToCart } from '@/lib/services/medusaCart.service';

import { PackageHeader } from './package-header';
import { ButtonTooltip } from './ui/button-tooltip';
import { getAnalysisElementMedusaProductIds } from '@/utils/medusa-product';

export interface IAnalysisPackage {
  titleKey: string;
  price: number;
  tagColor: string;
  descriptionKey: string;
}

export default function SelectAnalysisPackage({
  analysisPackage,
  countryCode,
}: {
  analysisPackage: StoreProduct
  countryCode: string,
}) {
  const router = useRouter();
  const { t, i18n: { language } } = useTranslation();
  
  const [isAddingToCart, setIsAddingToCart] = useState(false);
  const handleSelect = async (selectedVariant: StoreProductVariant) => {
    if (!selectedVariant?.id) return null

    setIsAddingToCart(true);
    await handleAddToCart({
      selectedVariant,
      countryCode,
    });
    setIsAddingToCart(false);
    router.push('/home/cart');
  }

  const titleKey = analysisPackage.title;
  const analysisElementMedusaProductIds = getAnalysisElementMedusaProductIds([analysisPackage]);
  const nrOfAnalyses = analysisElementMedusaProductIds.length;
  const description = analysisPackage.description ?? '';
  const subtitle = analysisPackage.subtitle ?? '';
  const variant = analysisPackage.variants?.[0];

  if (!variant) {
    return null;
  }

  const price = variant.calculated_price?.calculated_amount ?? 0;

  return (
    <Card key={titleKey}>
      <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={t(titleKey)}
          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(variant)} isLoading={isAddingToCart}>
          {!isAddingToCart && <Trans i18nKey='order-analysis-package:selectThisPackage' />}
        </Button>
      </CardFooter>
    </Card>
  );
}
