"use client";

import Image from "next/image";
import { useMemo, useState } from "react";
import { Button } from "@/components/ui/button";
import {
  getProductDiscountLabel,
  hasRealProductDiscount,
} from "@/lib/storefront-pricing";
import { dispatchStorefrontCartUpdated } from "@/lib/storefront-events";
import { detonexFigmaAssets } from "@/lib/detonex-figma";
import type {
  StorefrontCart,
  StorefrontProductDetail,
  StorefrontProductVariation,
} from "@/types/storefront";

export function ProductPurchasePanel({
  product,
}: {
  product: StorefrontProductDetail;
}) {
  const [quantity, setQuantity] = useState(1);
  const [selectedAttributes, setSelectedAttributes] = useState<Record<string, string>>(
    () =>
      Object.fromEntries(
        (product.variations[0]?.attributes ?? []).map((attribute) => [
          attribute.key,
          attribute.value,
        ]),
      ),
  );
  const [isAdding, setIsAdding] = useState(false);

  const groupedAttributes = useMemo(() => {
    const groups = new Map<string, { label: string; values: string[] }>();

    for (const variation of product.variations) {
      for (const attribute of variation.attributes) {
        const existing = groups.get(attribute.key);

        if (!existing) {
          groups.set(attribute.key, {
            label: attribute.label,
            values: [attribute.value],
          });
          continue;
        }

        if (!existing.values.includes(attribute.value)) {
          existing.values.push(attribute.value);
        }
      }
    }

    return Array.from(groups.entries()).map(([key, value]) => ({
      key,
      label: value.label,
      values: value.values,
    }));
  }, [product.variations]);

  const selectedVariation = useMemo<StorefrontProductVariation | null>(() => {
    if (product.variations.length === 0) {
      return null;
    }

    return (
      product.variations.find((variation) =>
        variation.attributes.every(
          (attribute) => selectedAttributes[attribute.key] === attribute.value,
        ),
      ) ?? null
    );
  }, [product.variations, selectedAttributes]);

  const resolvedPrice = selectedVariation?.price || product.price;
  const resolvedRegularPrice =
    selectedVariation?.regularPrice || product.regularPrice;
  const resolvedLowestPrice30d =
    selectedVariation?.lowestPrice30d || product.lowestPrice30d;
  const isResolvedInStock = selectedVariation
    ? selectedVariation.isInStock
    : product.isInStock;
  const discountLabel = getProductDiscountLabel({
    isOnSale: selectedVariation ? selectedVariation.isOnSale : product.isOnSale,
    regularPrice: resolvedRegularPrice,
    salePrice: selectedVariation?.salePrice || product.salePrice,
  });
  const showRegularPrice = hasRealProductDiscount({
    isOnSale: selectedVariation ? selectedVariation.isOnSale : product.isOnSale,
    regularPrice: resolvedRegularPrice,
    salePrice: selectedVariation?.salePrice || product.salePrice,
  });
  const swatchGroup = groupedAttributes[0] ?? null;
  const galleryImages =
    product.gallery.length > 0
      ? product.gallery
      : product.featuredImage
        ? [product.featuredImage]
        : [];
  const activeSwatchValue = swatchGroup
    ? selectedAttributes[swatchGroup.key] || swatchGroup.values[0] || ""
    : "";

  async function handleAddToCart() {
    try {
      setIsAdding(true);

      if (
        product.variations.length > 0 &&
        (!selectedVariation || !selectedVariation.isInStock)
      ) {
        return;
      }

      const response = await fetch("/api/cart/items", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          id: product.id,
          quantity,
          variation: selectedVariation?.attributes.map((attribute) => ({
            attribute: attribute.key,
            value: attribute.slug || attribute.value,
          })),
        }),
      });

      const payload = (await response.json()) as StorefrontCart | { message?: string };

      if (!response.ok) {
        throw new Error(
          "message" in payload && payload.message
            ? payload.message
            : "Dodavanje u košaricu nije uspjelo.",
        );
      }

      dispatchStorefrontCartUpdated(payload as StorefrontCart, "add-item");
    } finally {
      setIsAdding(false);
    }
  }

  return (
    <div className="space-y-5">
      {product.variations.length > 0 && (swatchGroup || groupedAttributes.length > 0) ? (
        <div className="space-y-[10px]">
          {swatchGroup ? (
            <p className="text-[16px] font-bold leading-[1.5] tracking-[-0.02em] text-primary">
              {swatchGroup.label}: <span className="font-medium">{activeSwatchValue}</span>
            </p>
          ) : null}
          <div className="flex flex-wrap items-center gap-[10px]">
            {(swatchGroup?.values ?? []).slice(0, 3).map((value, index) => {
              const isActive = activeSwatchValue === value;
              const image = galleryImages[index] || galleryImages[0] || product.featuredImage;

              return (
                <button
                  key={value}
                  type="button"
                  onClick={
                    swatchGroup
                      ? () =>
                          setSelectedAttributes((current) => ({
                            ...current,
                            [swatchGroup.key]: value,
                          }))
                      : undefined
                  }
                  className="relative inline-flex h-16 w-16 cursor-pointer overflow-hidden rounded-[8px]"
                >
                  <div className="relative h-full w-full overflow-hidden rounded-[8px] bg-white p-2">
                    {image ? (
                      <div className="relative h-full w-full">
                        <Image
                          src={image.src}
                          alt={image.alt || product.name}
                          fill
                          sizes="64px"
                          className="object-contain"
                        />
                      </div>
                    ) : null}
                    <span
                      aria-hidden="true"
                      className="pointer-events-none absolute inset-0 rounded-[8px]"
                      style={{
                        boxShadow: isActive
                          ? "inset 0 0 0 2px #F26D26"
                          : "inset 0 0 0 1px rgba(0, 0, 0, 0.10)",
                      }}
                    />
                  </div>
                  <span className="sr-only">{value}</span>
                </button>
              );
            })}
          </div>
        </div>
      ) : null}

      <div className="space-y-[10px]">
        {discountLabel ? (
          <div className="inline-flex items-center rounded-[4px] bg-accent/10 px-2 py-1">
            <p className="text-[14px] font-bold leading-[1.2] tracking-[-0.02em] text-accent">
              {discountLabel}
            </p>
          </div>
        ) : null}

        <div className="flex flex-wrap items-end gap-[10px]">
          <p className="text-[28px] font-bold leading-[1.2] tracking-[-0.03em] text-primary">
            {resolvedPrice}
          </p>
          <p className="pb-px text-[14px] font-medium leading-[1.5] tracking-[-0.01em] text-primary/60">
            PDV uključen
          </p>
        </div>
        {showRegularPrice && resolvedRegularPrice ? (
          <p className="text-[20px] font-semibold leading-[1.2] tracking-[-0.03em] text-primary/60 line-through">
            {resolvedRegularPrice}
          </p>
        ) : null}
      </div>

      <div className="space-y-4">
        {groupedAttributes.length > 0 ? (
          <div className="grid gap-4 sm:grid-cols-2">
            {groupedAttributes.slice(1).map((group) => (
              <label key={group.key} className="space-y-2">
                <span className="block text-sm font-semibold text-primary">
                  {group.label}
                </span>
                <select
                  className="h-12 w-full cursor-pointer rounded-control border border-line bg-white px-4 text-sm text-primary"
                  value={selectedAttributes[group.key] ?? ""}
                  onChange={(event) =>
                    setSelectedAttributes((current) => ({
                      ...current,
                      [group.key]: event.target.value,
                    }))
                  }
                >
                  <option value="">Odaberi</option>
                  {group.values.map((value) => (
                    <option key={value} value={value}>
                      {value}
                    </option>
                  ))}
                </select>
              </label>
            ))}
          </div>
        ) : null}

        <div className="flex items-start gap-3">
          <div
            className="flex h-12 w-[100px] min-w-[100px] max-w-[100px] shrink-0 items-center justify-between rounded-[6px] bg-white px-2"
            style={{ boxShadow: "inset 0 0 0 1px rgba(0, 0, 0, 0.10)" }}
          >
            <button
              type="button"
              onClick={() => setQuantity((current) => Math.max(1, current - 1))}
              className="inline-flex size-4 shrink-0 cursor-pointer items-center justify-center"
            >
              <Image
                src={detonexFigmaAssets.icons.productQtyMinus}
                alt="Smanji količinu"
                width={16}
                height={16}
                className="size-4"
              />
            </button>
            <span className="text-center text-[14px] font-bold leading-[1.5] tracking-[-0.01em] text-primary">
              {quantity}
            </span>
            <button
              type="button"
              onClick={() => setQuantity((current) => current + 1)}
              className="inline-flex size-4 shrink-0 cursor-pointer items-center justify-center"
            >
              <Image
                src={detonexFigmaAssets.icons.productQtyPlus}
                alt="Povećaj količinu"
                width={16}
                height={16}
                className="size-4"
              />
            </button>
          </div>

          <Button
            className="min-w-0 flex-[1_0_0] cursor-pointer rounded-[6px]"
            size="md"
            onClick={handleAddToCart}
            disabled={isAdding || !isResolvedInStock}
          >
            {isAdding ? "Dodavanje..." : "Dodaj u košaricu"}
          </Button>
        </div>
      </div>

      <div className="space-y-2 text-[14px] font-medium leading-[1.5] tracking-[-0.01em] text-primary">
        <p>
          Dostupnost:{" "}
          <span className={isResolvedInStock ? "font-bold text-accent" : "font-bold text-danger"}>
            {isResolvedInStock ? "Raspoloživo" : "Nije raspoloživo"}
          </span>
        </p>
        {resolvedLowestPrice30d ? (
          <p>
            Najniža cijena u zadnjih 30 dana:{" "}
            <span className="font-bold text-accent">{resolvedLowestPrice30d}</span>
          </p>
        ) : null}
      </div>
    </div>
  );
}
