"use client";

import { HeartPulse, ShoppingCart } from 'lucide-react';

import { Button } from '@kit/ui/button';
import {
  Card,
  CardHeader,
  CardFooter,
} from '@kit/ui/card';
import { StoreProduct, StoreProductVariant } from '@medusajs/types';
import { useState } from 'react';
import { handleAddToCart } from '~/lib/services/medusaCart.service';
import { useRouter } from 'next/navigation';

export default function OrderAnalysesCards({
  analyses,
  countryCode,
}: {
  analyses: StoreProduct[];
  countryCode: string;
}) {
  const router = useRouter();
  
  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');
  }

  return (
    <div className="grid grid-cols-3 gap-6 mt-4">
      {analyses.map(({
        title,
        variants
      }) => (
        <Card
          key={title}
          variant="gradient-success"
          className="flex flex-col justify-between"
        >
          <CardHeader className="items-end-safe">
            <div className='flex size-8 items-center-safe justify-center-safe rounded-full text-white bg-warning'>
              <Button
                size="icon"
                variant="outline"
                className="px-2 text-black"
                onClick={() => handleSelect(variants![0]!)}
                disabled={isAddingToCart}
              >
                <ShoppingCart className="size-4 stroke-2" />
              </Button>
            </div>
          </CardHeader>
          <CardFooter className="flex flex-col items-start gap-2">
            <div
              className={'flex size-8 items-center-safe justify-center-safe rounded-full text-white bg-primary\/10 mb-6'}
            >
              <HeartPulse className="size-4 fill-green-500" />
            </div>
            <h5>
              {title}
            </h5>
          </CardFooter>
        </Card>
      ))}
    </div>
  );
}
