'use client';

import { useState } from 'react';

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

import type { AdminProductVariant, StoreProduct } from '@medusajs/types';
import { useTranslation } from 'react-i18next';

import { Button } from '@kit/ui/button';
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
} from '@kit/ui/card';
import { toast } from '@kit/ui/sonner';
import { Spinner } from '@kit/ui/spinner';
import { Trans } from '@kit/ui/trans';

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

import { pathsConfig } from '../config';
import { PackageHeader } from './package-header';
import { ButtonTooltip } from './ui/button-tooltip';

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

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(pathsConfig.app.cart);
    } catch (e) {
      toast.error(
        <Trans
          i18nKey={'order-analysis-package:analysisPackageAddToCartError'}
        />,
      );
      setIsAddingToCart(false);
      console.error(e);
    }
  };

  return (
    <Card key={title} className="flex flex-col">
      <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-2 text-center">
        <PackageHeader
          title={title}
          tagColor="bg-cyan"
          analysesNr={t('product:nrOfAnalyses', { nr: nrOfAnalyses })}
          language={language}
          price={price}
        />
        <CardDescription>{subtitle}</CardDescription>
      </CardContent>
      <CardFooter className="mt-auto">
        <Button
          className="w-full text-[10px] sm:text-sm"
          onClick={handleSelect}
        >
          {isAddingToCart ? (
            <Spinner />
          ) : (
            <Trans i18nKey="order-analysis-package:selectThisPackage" />
          )}
        </Button>
      </CardFooter>
    </Card>
  );
}
