"use client";

import Image from "next/image";
import Link from "next/link";
import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import {
  STOREFRONT_CART_UPDATED,
  dispatchStorefrontCartUpdated,
  type StorefrontCartUpdateReason,
} from "@/lib/storefront-events";
import { detonexFigmaAssets } from "@/lib/detonex-figma";
import { useOptimisticCartQuantity } from "@/lib/use-optimistic-cart-quantity";
import type { StorefrontCart } from "@/types/storefront";

function isCartEventDetail(
  value: unknown,
): value is {
  cart: StorefrontCart;
  count: number;
  reason?: StorefrontCartUpdateReason;
} {
  return Boolean(
    value &&
      typeof value === "object" &&
      "cart" in value &&
      "count" in value,
  );
}

export function CartPopupDrawer({ initialCart }: { initialCart: StorefrontCart }) {
  const [cart, setCart] = useState<StorefrontCart>(initialCart);
  const [isOpen, setIsOpen] = useState(false);
  const [busyKey, setBusyKey] = useState<string | null>(null);
  const { isQuantitySyncing, updateItemQuantity } = useOptimisticCartQuantity({
    setCart,
  });
  const hasPendingQuantitySync = cart.items.some((item) => isQuantitySyncing(item.key));

  useEffect(() => {
    function handleCartUpdated(event: Event) {
      const detail = (event as CustomEvent).detail;

      if (!isCartEventDetail(detail)) {
        return;
      }

      setCart(detail.cart);

      if (detail.reason === "add-item") {
        setIsOpen(true);
      }
    }
    window.addEventListener(STOREFRONT_CART_UPDATED, handleCartUpdated);

    return () => {
      window.removeEventListener(STOREFRONT_CART_UPDATED, handleCartUpdated);
    };
  }, []);

  useEffect(() => {
    if (!isOpen) {
      return;
    }

    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";

    return () => {
      document.body.style.overflow = previousOverflow;
    };
  }, [isOpen]);

  async function removeCartItem(key: string) {
    try {
      setBusyKey(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");
    } finally {
      setBusyKey(null);
    }
  }

  if (!isOpen) {
    return null;
  }

  return (
    <div className="fixed inset-0 z-[110]">
      <button
        type="button"
        aria-label="Zatvori popup košarice"
        className="absolute inset-0 bg-black/20"
        onClick={() => setIsOpen(false)}
      />

      <aside className="absolute right-0 top-0 flex h-full w-full max-w-[520px] flex-col bg-white shadow-[0_0_40px_rgba(0,0,0,0.12)]">
        <div className="flex h-20 items-center justify-between border-b border-black/10 px-6">
          <h2 className="text-[24px] font-bold leading-7 tracking-[-0.03em] text-primary">
            Košarica
          </h2>
          <button
            type="button"
            onClick={() => setIsOpen(false)}
            className="inline-flex size-[38px] cursor-pointer items-center justify-center rounded-full border border-black/10 text-[24px] leading-none text-primary"
            aria-label="Zatvori"
          >
            ×
          </button>
        </div>

        <div className="flex-1 overflow-y-auto px-6 py-6">
          <div className="space-y-5">
            {cart.items.slice(0, 3).map((item) => (
              <article key={item.key} className="flex gap-4">
                <div
                  className="h-[110px] w-[110px] shrink-0 rounded-[8px] p-px"
                  style={{ backgroundColor: "rgba(0, 0, 0, 0.10)" }}
                >
                  <Link
                    href={item.href}
                    onClick={() => setIsOpen(false)}
                    className="block h-full w-full overflow-hidden rounded-[7px] bg-white p-3"
                  >
                    <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>

                <div className="min-w-0 flex-1">
                  <div className="flex items-start gap-4">
                    <Link
                      href={item.href}
                      onClick={() => setIsOpen(false)}
                      className="min-w-0 flex-1"
                    >
                      <h3 className="text-[16px] font-bold leading-[1.3] tracking-[-0.03em] text-primary">
                        {item.name}
                      </h3>
                    </Link>
                    <button
                      type="button"
                      onClick={() => removeCartItem(item.key)}
                      disabled={busyKey === item.key}
                      className="inline-flex size-4 cursor-pointer items-center justify-center"
                      aria-label="Ukloni proizvod"
                    >
                      <Image
                        src={detonexFigmaAssets.icons.cartRemove}
                        alt=""
                        width={16}
                        height={16}
                        className="size-4"
                      />
                    </button>
                  </div>

                  <div className="mt-[18px] flex items-end justify-between gap-4">
                    <div className="space-y-px">
                      <p className="text-[14px] font-medium 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 className="flex h-8 items-center rounded-[6px] border border-black/10 bg-white">
                      <button
                        type="button"
                        className="inline-flex h-8 w-8 cursor-pointer items-center justify-center"
                        onClick={() =>
                          updateItemQuantity(item.key, Math.max(1, item.quantity - 1))
                        }
                      >
                        <Image
                          src={detonexFigmaAssets.icons.productQtyMinus}
                          alt="Smanji količinu"
                          width={12}
                          height={12}
                          className="size-3"
                        />
                      </button>
                      <span className="inline-flex w-5 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 h-8 w-8 cursor-pointer items-center justify-center"
                        onClick={() => updateItemQuantity(item.key, item.quantity + 1)}
                      >
                        <Image
                          src={detonexFigmaAssets.icons.productQtyPlus}
                          alt="Povećaj količinu"
                          width={12}
                          height={12}
                          className="size-3"
                        />
                      </button>
                    </div>
                  </div>

                </div>
              </article>
            ))}
          </div>
        </div>

        <div className="space-y-3 px-6 py-6">
          <Button
            href="/cart"
            variant="secondary"
            size="md"
            className="w-full border border-[rgba(0,0,0,0.10)] bg-white hover:bg-muted-surface disabled:opacity-60"
            onClick={() => setIsOpen(false)}
            disabled={hasPendingQuantitySync}
          >
            Pregledaj košaricu
          </Button>
          <Button
            href="/checkout"
            size="md"
            className="w-full disabled:opacity-60"
            onClick={() => setIsOpen(false)}
            disabled={hasPendingQuantitySync}
          >
            Nastavi na plaćanje
          </Button>
        </div>
      </aside>
    </div>
  );
}
