"use client";

import Image from "next/image";
import Link from "next/link";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/cn";
import {
  dispatchStorefrontWishlistAdded,
  dispatchStorefrontCartUpdated,
  dispatchStorefrontWishlistUpdated,
} from "@/lib/storefront-events";
import { buildWishlistItemFromCartItem } from "@/lib/storefront-wishlist-item";
import { useOptimisticCartQuantity } from "@/lib/use-optimistic-cart-quantity";
import { detonexFigmaAssets } from "@/lib/detonex-figma";
import type { StorefrontCart, StorefrontWishlist } from "@/types/storefront";

export function CartPageClient({ initialCart }: { initialCart: StorefrontCart }) {
  const [cart, setCart] = useState(initialCart);
  const [busyAction, setBusyAction] = useState<{
    key: string;
    type: "remove" | "add-to-wishlist";
  } | null>(null);
  const [message, setMessage] = useState<string | null>(null);
  const { cancelItemQuantitySync, updateItemQuantity } = useOptimisticCartQuantity({
    setCart,
    onError: setMessage,
  });

  async function removeCartItem(key: string) {
    try {
      setBusyAction({ key, type: "remove" });
      setMessage(null);
      cancelItemQuantitySync(key);

      const response = await fetch(`/api/cart/items/${encodeURIComponent(key)}`, {
        method: "DELETE",
      });
      const payload = (await response.json()) as StorefrontCart | { message?: string };

      if (!response.ok) {
        throw new Error(
          "message" in payload && payload.message
            ? payload.message
            : "Uklanjanje proizvoda nije uspjelo.",
        );
      }

      setCart(payload as StorefrontCart);
      dispatchStorefrontCartUpdated(payload as StorefrontCart, "remove-item");
    } catch (error) {
      setMessage(
        error instanceof Error
          ? error.message
          : "Uklanjanje proizvoda nije uspjelo.",
      );
    } finally {
      setBusyAction(null);
    }
  }

  async function addCartItemToWishlist(item: StorefrontCart["items"][number]) {
    try {
      setBusyAction({ key: item.key, type: "add-to-wishlist" });
      setMessage(null);
      cancelItemQuantitySync(item.key);

      const wishlistResponse = await fetch("/api/wishlist/items", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(buildWishlistItemFromCartItem(item)),
      });
      const wishlistPayload = (await wishlistResponse.json()) as
        | StorefrontWishlist
        | { message?: string };

      if (!wishlistResponse.ok) {
        throw new Error(
          "message" in wishlistPayload && wishlistPayload.message
            ? wishlistPayload.message
            : "Dodavanje u listu želja nije uspjelo.",
        );
      }

      dispatchStorefrontWishlistUpdated(wishlistPayload as StorefrontWishlist);
      dispatchStorefrontWishlistAdded(buildWishlistItemFromCartItem(item));
      setMessage(null);
    } catch (error) {
      setMessage(
        error instanceof Error
          ? error.message
          : "Dodavanje u listu želja nije uspjelo.",
      );
    } finally {
      setBusyAction(null);
    }
  }

  return (
    <div className="space-y-[42px]">
      <header>
        <h1 className="text-[38px] font-bold leading-[1.2] tracking-[-0.03em] text-primary">
          Košarica
        </h1>
      </header>

      <div className="grid gap-[60px] xl:grid-cols-[780px_minmax(0,400px)]">
        <section className="space-y-0">
          {cart.items.length > 0 ? (
            cart.items.map((item, index) => {
              const isRemoving =
                busyAction?.key === item.key && busyAction.type === "remove";
              const isMovingToWishlist =
                busyAction?.key === item.key &&
                busyAction.type === "add-to-wishlist";
              const isItemBusy = isRemoving || isMovingToWishlist;

              return (
              <article
                key={item.key}
                className={cn(
                  "flex gap-6",
                  index > 0 && "mt-6 border-t border-black/10 pt-6",
                )}
              >
                <Link
                  href={item.href}
                  className="block h-[110px] w-[110px] shrink-0 overflow-hidden rounded-[8px] border bg-white p-3"
                  style={{ borderColor: "rgba(0, 0, 0, 0.20)" }}
                >
                  <div className="relative h-full w-full">
                    <Image
                      src={item.image?.src || detonexFigmaAssets.productFallbackImage}
                      alt={item.image?.alt || item.name}
                      fill
                      sizes="110px"
                      className="object-contain"
                    />
                  </div>
                </Link>

                <div className="min-w-0 flex-1 space-y-[18px]">
                  <div className="flex items-start justify-between gap-[42px] text-primary">
                    <div className="min-w-0 flex-1 space-y-1">
                      <p className="text-[14px] font-medium uppercase leading-[1.5] tracking-[-0.02em] text-primary/60">
                        {item.label}
                      </p>
                      <Link href={item.href} className="block">
                        <h2 className="text-[16px] font-bold leading-[1.2] tracking-[-0.03em] text-primary">
                          {item.name}
                        </h2>
                      </Link>
                    </div>

                    <div className="shrink-0 text-right">
                      <p className="text-[16px] font-bold leading-[1.5] tracking-[-0.02em] text-primary">
                        {item.total}
                      </p>
                      <p className="text-[14px] font-medium leading-[1.5] tracking-[-0.02em] text-primary/60">
                        {item.unitPrice} / kom
                      </p>
                    </div>
                  </div>

                  <div className="flex items-end justify-between gap-6">
                    <div className="space-y-[2px]">
                      <button
                        type="button"
                        className="flex cursor-pointer items-center gap-2 text-[14px] font-medium leading-[1.5] tracking-[-0.02em] text-primary"
                        onClick={() => removeCartItem(item.key)}
                        disabled={isItemBusy}
                      >
                        <Image
                          src={detonexFigmaAssets.icons.cartRemove}
                          alt=""
                          width={14}
                          height={14}
                          className="size-[14px]"
                        />
                        <span>{isRemoving ? "Uklanjanje..." : "Ukloni proizvod"}</span>
                      </button>

                      <button
                        type="button"
                        className="flex cursor-pointer items-center gap-2 text-[14px] font-medium leading-[1.5] tracking-[-0.02em] text-primary"
                        onClick={() => addCartItemToWishlist(item)}
                        disabled={isItemBusy}
                      >
                        <Image
                          src={detonexFigmaAssets.icons.cartSaveForLater}
                          alt=""
                          width={14}
                          height={14}
                          className="size-[14px]"
                        />
                        <span>Označi za kasnije</span>
                      </button>
                    </div>

                    <div className="flex h-12 w-[132px] min-w-[132px] max-w-[132px] shrink-0 items-center rounded-[6px] border border-black/10 bg-white">
                      <button
                        type="button"
                        className="inline-flex size-12 cursor-pointer items-center justify-center"
                        onClick={() => {
                          setMessage(null);
                          updateItemQuantity(item.key, Math.max(1, item.quantity - 1));
                        }}
                      >
                        <Image
                          src={detonexFigmaAssets.icons.productQtyMinus}
                          alt="Smanji količinu"
                          width={16}
                          height={16}
                          className="size-4"
                        />
                      </button>
                      <span className="inline-flex w-9 items-center justify-center text-[14px] font-bold leading-[1.5] tracking-[-0.01em] text-primary">
                        {item.quantity}
                      </span>
                      <button
                        type="button"
                        className="inline-flex size-12 cursor-pointer items-center justify-center"
                        onClick={() => {
                          setMessage(null);
                          updateItemQuantity(item.key, item.quantity + 1);
                        }}
                      >
                        <Image
                          src={detonexFigmaAssets.icons.productQtyPlus}
                          alt="Povećaj količinu"
                          width={16}
                          height={16}
                          className="size-4"
                        />
                      </button>
                    </div>
                  </div>

                  {item.variation.length > 0 ? (
                    <div className="space-y-1">
                      {item.variation.map((variation) => (
                        <p
                          key={`${item.key}-${variation.label}`}
                          className="text-[14px] font-medium leading-[1.5] tracking-[-0.02em] text-primary/60"
                        >
                          {variation.label}: {variation.value}
                        </p>
                      ))}
                    </div>
                  ) : null}
                </div>
              </article>
              );
            })
          ) : (
            <div className="rounded-[6px] border border-dashed border-line bg-surface p-8">
              <p className="max-w-2xl text-base leading-7 text-primary/72">
                Trenutno nema proizvoda u košarici.
              </p>
            </div>
          )}

          {message ? <p className="text-[14px] text-primary/72">{message}</p> : null}
        </section>

        <aside className="self-start rounded-[6px] bg-muted-surface p-6">
          <div className="space-y-4">
            <h2 className="text-[20px] font-bold leading-[1.2] tracking-[-0.03em] text-primary">
              Sažetak
            </h2>
            <div className="flex items-start justify-between gap-4 text-[16px] leading-[1.2] tracking-[-0.03em] text-primary">
              <span>Iznos (s PDV-om)</span>
              <span className="font-medium">{cart.total}</span>
            </div>
          </div>

          <Button
            href="/checkout"
            className="mt-6 w-full rounded-[6px]"
            disabled={cart.isEmpty}
          >
            Nastavi na plaćanje
          </Button>
        </aside>
      </div>
    </div>
  );
}
