"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { PopShell } from "@/components/pop/hardcoded";
import { PurchaseInbound } from "@/components/pop/hardcoded/inbound";
import { useCartSync } from "@/components/pop/hardcoded/common/useCartSync";

export default function PurchaseInboundPage() {
  const router = useRouter();
  const cart = useCartSync("pop-purchase-inbound", "purchase_detail");
  const [saving, setSaving] = useState(false);

  const handleCartClick = async () => {
    if (cart.isDirty) {
      setSaving(true);
      const ok = await cart.saveToDb();
      setSaving(false);
      if (!ok) return; // save failed, don't navigate
    }
    router.push("/pop/inbound/cart");
  };

  return (
    <PopShell
      showBanner={false}
      title="구매입고"
      headerRight={
        <button
          onClick={handleCartClick}
          disabled={saving}
          className="relative w-11 h-11 rounded-xl bg-white/10 flex items-center justify-center text-white hover:bg-white/20 active:scale-95 transition-all"
        >
          {saving ? (
            <svg className="animate-spin w-5 h-5" fill="none" viewBox="0 0 24 24">
              <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
              <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
            </svg>
          ) : (
            <svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22" />
            </svg>
          )}
          {cart.cartCount > 0 && (
            <span className={`absolute -top-1 -right-1 min-w-[20px] h-5 rounded-full text-[10px] font-bold text-white flex items-center justify-center
              ${cart.isDirty ? "bg-orange-500 animate-pulse" : "bg-red-500"}
            `}>
              {cart.cartCount}
            </span>
          )}
        </button>
      }
    >
      <PurchaseInbound cart={cart} />
    </PopShell>
  );
}
