"use client";

import Image from "next/image";
import type { ReactNode } from "react";
import { useEffect, useRef, useState } from "react";
import {
  dispatchStorefrontWishlistAdded,
  dispatchStorefrontWishlistUpdated,
} from "@/lib/storefront-events";
import { detonexFigmaAssets } from "@/lib/detonex-figma";
import { buildWishlistItemFromProductDetail } from "@/lib/storefront-wishlist-item";
import type { StorefrontProductDetail, StorefrontWishlist } from "@/types/storefront";

function ShareIcon({
  children,
}: {
  children: ReactNode;
}) {
  return (
    <span className="inline-flex size-9 shrink-0 items-center justify-center rounded-full border border-black/10 bg-white text-primary">
      {children}
    </span>
  );
}

export function ProductHeaderActions({
  product,
}: {
  product: StorefrontProductDetail;
}) {
  const [isShareMenuOpen, setIsShareMenuOpen] = useState(false);
  const shareMenuRef = useRef<HTMLDivElement | null>(null);
  const shareUrl =
    typeof window !== "undefined" ? window.location.href : product.href;
  const shareText = `${product.name} ${shareUrl}`;

  useEffect(() => {
    if (!isShareMenuOpen) {
      return undefined;
    }

    function handlePointerDown(event: MouseEvent) {
      if (!shareMenuRef.current?.contains(event.target as Node)) {
        setIsShareMenuOpen(false);
      }
    }

    function handleEscape(event: KeyboardEvent) {
      if (event.key === "Escape") {
        setIsShareMenuOpen(false);
      }
    }

    document.addEventListener("mousedown", handlePointerDown);
    document.addEventListener("keydown", handleEscape);

    return () => {
      document.removeEventListener("mousedown", handlePointerDown);
      document.removeEventListener("keydown", handleEscape);
    };
  }, [isShareMenuOpen]);

  async function handleAddToWishlist() {
    try {
      const response = await fetch("/api/wishlist/items", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(buildWishlistItemFromProductDetail(product)),
      });
      const payload = (await response.json()) as StorefrontWishlist | { message?: string };

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

      dispatchStorefrontWishlistUpdated(payload as StorefrontWishlist);
      dispatchStorefrontWishlistAdded(buildWishlistItemFromProductDetail(product));
    } catch {}
  }

  function handleShareTrigger() {
    setIsShareMenuOpen((current) => !current);
  }

  async function handleCopyLink() {
    try {
      await navigator.clipboard.writeText(shareUrl);
      setIsShareMenuOpen(false);
    } catch {}
  }

  return (
    <div className="flex items-center gap-8">
        <div ref={shareMenuRef} className="relative flex items-center">
          <button
            type="button"
            onClick={handleShareTrigger}
            aria-haspopup="menu"
            aria-expanded={isShareMenuOpen}
            className="inline-flex size-6 cursor-pointer items-center justify-center align-middle"
          >
            <Image
              src={detonexFigmaAssets.icons.productActionOne}
              alt="Podijeli proizvod"
              width={24}
              height={24}
              className="size-6"
            />
          </button>

          {isShareMenuOpen ? (
            <div className="absolute right-0 top-full z-20 mt-3 rounded-[8px] border border-black/10 bg-white p-3 shadow-[0_16px_40px_rgba(32,32,33,0.12)]">
              <div className="flex items-center gap-2">
                <a
                  href={`https://wa.me/?text=${encodeURIComponent(shareText)}`}
                  target="_blank"
                  rel="noreferrer"
                  onClick={() => setIsShareMenuOpen(false)}
                  aria-label="Podijeli na WhatsAppu"
                  className="rounded-[6px] p-1"
                >
                  <ShareIcon>
                    <svg viewBox="0 0 24 24" className="size-[18px] fill-current" aria-hidden="true">
                      <path d="M12 2a10 10 0 0 0-8.67 14.98L2 22l5.18-1.3A10 10 0 1 0 12 2Zm5.3 14.37c-.22.63-1.27 1.17-1.75 1.25-.45.08-1.03.12-1.66-.09-.38-.12-.87-.28-1.5-.55-2.64-1.14-4.37-3.95-4.5-4.12-.13-.18-1.07-1.42-1.07-2.72 0-1.3.68-1.93.92-2.2.23-.27.5-.34.67-.34.17 0 .33 0 .48.01.15 0 .36-.06.56.42.21.5.71 1.72.77 1.84.06.13.1.28.02.45-.08.17-.12.28-.24.43-.12.15-.25.34-.36.45-.12.12-.24.25-.1.5.13.25.6.98 1.28 1.59.88.79 1.61 1.03 1.86 1.15.25.13.39.1.53-.06.15-.17.63-.73.8-.98.17-.25.34-.21.57-.13.24.08 1.48.7 1.73.82.25.13.42.19.48.3.06.1.06.6-.16 1.23Z" />
                    </svg>
                  </ShareIcon>
                </a>

                <a
                  href={`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(shareUrl)}`}
                  target="_blank"
                  rel="noreferrer"
                  onClick={() => setIsShareMenuOpen(false)}
                  aria-label="Podijeli na Facebooku"
                  className="rounded-[6px] p-1"
                >
                  <ShareIcon>
                    <svg viewBox="0 0 24 24" className="size-[18px] fill-current" aria-hidden="true">
                      <path d="M13.28 22v-8.2H16l.4-3.2h-3.12V8.56c0-.93.26-1.56 1.6-1.56h1.7V4.14c-.3-.04-1.3-.14-2.47-.14-2.45 0-4.12 1.5-4.12 4.24v2.36H7.2v3.2H10V22h3.28Z" />
                    </svg>
                  </ShareIcon>
                </a>

                <a
                  href={`mailto:?subject=${encodeURIComponent(product.name)}&body=${encodeURIComponent(shareUrl)}`}
                  onClick={() => setIsShareMenuOpen(false)}
                  aria-label="Podijeli e-mailom"
                  className="rounded-[6px] p-1"
                >
                  <ShareIcon>
                    <svg viewBox="0 0 24 24" className="size-[18px] fill-current" aria-hidden="true">
                      <path d="M3 6.75A1.75 1.75 0 0 1 4.75 5h14.5A1.75 1.75 0 0 1 21 6.75v10.5A1.75 1.75 0 0 1 19.25 19H4.75A1.75 1.75 0 0 1 3 17.25V6.75Zm1.83-.25L12 11.73l7.17-5.23H4.83ZM19.5 8l-6.9 5.03a1 1 0 0 1-1.2 0L4.5 8v9.25c0 .14.11.25.25.25h14.5a.25.25 0 0 0 .25-.25V8Z" />
                    </svg>
                  </ShareIcon>
                </a>

                <button
                  type="button"
                  onClick={handleCopyLink}
                  aria-label="Kopiraj link"
                  className="rounded-[6px] p-1"
                >
                  <ShareIcon>
                    <svg viewBox="0 0 24 24" className="size-[18px] stroke-current" fill="none" strokeWidth="1.8" aria-hidden="true">
                      <rect x="9" y="9" width="11" height="11" rx="2" />
                      <path d="M6 15H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v1" />
                    </svg>
                  </ShareIcon>
                </button>
              </div>

            </div>
          ) : null}
        </div>

        <button
          type="button"
          onClick={handleAddToWishlist}
          className="inline-flex size-6 cursor-pointer items-center justify-center align-middle"
        >
          <Image
            src={detonexFigmaAssets.icons.productActionTwo}
            alt="Dodaj u listu želja"
            width={24}
            height={24}
            className="size-6"
          />
        </button>
    </div>
  );
}
