"use client";

import { useEffect, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { useCartStore } from "@/lib/cart-store";
import { useAuthStore } from "@/lib/auth-store";
import { formatPrice, resolveMediaUrl } from "@/lib/utils";
import { useLanguage } from "@/lib/language-context";
import GateModal from "@/components/auth/GateModal";
import ColorSwatch from "@/components/ui/ColorSwatch";
import { useStorefrontConfig } from "@/lib/storefront-config-context";

export default function CartPage() {
  const { t } = useLanguage();
  const { website } = useStorefrontConfig();
  const allowGuestCheckout = !!website?.allow_guest_checkout;
  const isLoggedIn = useAuthStore((s) => s.isLoggedIn());
  const canProceedToCheckout = isLoggedIn || allowGuestCheckout;
  const [showCheckoutGate, setShowCheckoutGate] = useState(false);
  const {
    items,
    removeItem,
    updateQuantity,
    total,
    clearCart,
    applyValidation,
  } = useCartStore();

  // Validate cart against current inventory and cap quantities
  useEffect(() => {
    if (items.length === 0) return;
    fetch("/api/storefront-proxy/cart/validate", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        items: items.map((i) => ({ item_id: i.item_id, quantity: i.quantity })),
      }),
    })
      .then((r) => r.json())
      .then((data) => {
        if (data?.items?.length) {
          applyValidation(
            data.items.map((x: { item_id: number; available_qty: number }) => ({
              item_id: x.item_id,
              available_qty: x.available_qty ?? 0,
            })),
          );
        }
      })
      .catch(() => {});
  }, [items.length, applyValidation]);

  if (items.length === 0) {
    return (
      <div className="max-w-2xl mx-auto px-4 sm:px-6 py-12 sm:py-24 text-center">
        <div className="w-20 h-20 rounded-full bg-gray-100 flex items-center justify-center mx-auto mb-6">
          <svg
            className="w-10 h-10 text-gray-400"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            strokeWidth={1.25}
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"
            />
          </svg>
        </div>
        <h1 className="text-2xl font-bold text-gray-900 mb-2">
          {t.cart.empty}
        </h1>
        <p className="text-gray-500 mb-8">{t.cart.emptyAddHint}</p>
        <Link
          href="/products"
          className="btn-primary px-8 py-3.5 rounded-2xl inline-block font-semibold text-sm"
        >
          {t.common.browseProducts}
        </Link>
      </div>
    );
  }

  return (
    <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-6 sm:py-8">
      <div className="flex items-center justify-between mb-8">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">{t.cart.title}</h1>
          <p className="text-sm text-gray-400 mt-0.5">
            {items.length} {items.length === 1 ? "item" : "items"}
          </p>
        </div>
        <button
          onClick={clearCart}
          className="text-xs text-gray-400 hover:text-red-500 transition-colors font-medium flex items-center gap-1"
        >
          <svg
            className="w-3.5 h-3.5"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            strokeWidth={2}
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
            />
          </svg>
          {t.cart.clearCart}
        </button>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        {/* Items */}
        <div className="lg:col-span-2 space-y-3">
          {items.map((item) => (
            <div
              key={item.barcode}
              className="bg-white rounded-2xl border border-gray-100 p-4 flex flex-col sm:flex-row gap-4 items-stretch sm:items-start shadow-sm hover:shadow-md transition-shadow"
            >
              {/* Image */}
              <Link
                href={`/products/${item.barcode}`}
                className="w-20 h-20 bg-gray-50 rounded-xl overflow-hidden relative flex-shrink-0 border border-gray-100"
              >
                {item.image_url && resolveMediaUrl(item.image_url) ? (
                  <Image
                    src={resolveMediaUrl(item.image_url)!}
                    alt={item.name}
                    fill
                    className="object-cover"
                    sizes="80px"
                  />
                ) : (
                  <div className="w-full h-full flex items-center justify-center">
                    <svg
                      className="h-7 w-7 text-gray-300"
                      fill="none"
                      viewBox="0 0 24 24"
                      stroke="currentColor"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={1}
                        d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"
                      />
                    </svg>
                  </div>
                )}
              </Link>

              {/* Info */}
              <div className="flex-1 min-w-0">
                <Link
                  href={`/products/${item.barcode}`}
                  className="text-sm font-semibold text-gray-800 hover:underline truncate block"
                >
                  {item.name}
                </Link>
                <div className="flex flex-wrap items-center gap-1.5 mt-0.5">
                  {item.color && (
                    <ColorSwatch
                      name={item.color.name}
                      hex={item.color.hex}
                      size="sm"
                    />
                  )}
                  {item.size && (
                    <span className="text-xs text-gray-500 border border-gray-200 rounded px-1.5 py-0.5">
                      {item.size.name}
                    </span>
                  )}
                  {!item.color && !item.size && item.variant_label && (
                    <p className="text-xs text-gray-400">{item.variant_label}</p>
                  )}
                </div>
                <div className="flex items-center gap-2 mt-2">
                  <p
                    className="text-base font-bold"
                    style={{ color: "var(--color-primary)" }}
                  >
                    {formatPrice(item.price * item.quantity)}
                  </p>
                  <span className="text-xs text-gray-400">
                    ({formatPrice(item.price)} {t.cart.each})
                  </span>
                </div>
              </div>

              {/* Quantity + remove */}
              <div className="flex flex-col items-end gap-3 flex-shrink-0">
                <button
                  onClick={() => removeItem(item.barcode)}
                  className="text-gray-300 hover:text-red-400 transition-colors"
                  aria-label={t.cart.remove}
                >
                  <svg
                    className="h-4 w-4"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M6 18L18 6M6 6l12 12"
                    />
                  </svg>
                </button>
                <div className="flex items-center border border-gray-200 rounded-xl overflow-hidden">
                  <button
                    onClick={() =>
                      updateQuantity(item.barcode, item.quantity - 1)
                    }
                    className="w-8 h-8 flex items-center justify-center text-gray-500 hover:bg-gray-50 transition-colors text-base"
                  >
                    −
                  </button>
                  <span className="text-sm font-semibold w-8 text-center border-x border-gray-200">
                    {item.quantity}
                  </span>
                  <button
                    onClick={() =>
                      updateQuantity(item.barcode, item.quantity + 1)
                    }
                    disabled={
                      item.available_qty !== undefined &&
                      item.quantity >= item.available_qty
                    }
                    className="w-8 h-8 flex items-center justify-center text-gray-500 hover:bg-gray-50 transition-colors text-base disabled:opacity-40 disabled:cursor-not-allowed"
                  >
                    +
                  </button>
                </div>
              </div>
            </div>
          ))}
        </div>

        {/* Summary */}
        <div className="lg:col-span-1">
          <div className="bg-white rounded-2xl border border-gray-100 p-6 sticky top-20 shadow-sm">
            <h2 className="text-base font-bold text-gray-900 mb-5">
              {t.cart.orderSummary}
            </h2>
            <div className="space-y-2.5 text-sm text-gray-600 mb-5">
              {items.map((item) => (
                <div key={item.barcode} className="flex justify-between gap-2">
                  <span className="truncate text-gray-500">
                    {item.name}{" "}
                    <span className="text-gray-400">×{item.quantity}</span>
                  </span>
                  <span className="font-medium text-gray-800 flex-shrink-0">
                    {formatPrice(item.price * item.quantity)}
                  </span>
                </div>
              ))}
            </div>
            <div className="border-t border-gray-100 pt-4 mb-6">
              <div className="flex justify-between text-base font-bold text-gray-900">
                <span>{t.cart.total}</span>
                <span style={{ color: "var(--color-primary)" }}>
                  {formatPrice(total())}
                </span>
              </div>
              <p className="text-xs text-gray-400 mt-1">
                Taxes and shipping calculated at checkout
              </p>
            </div>
            {canProceedToCheckout ? (
              <Link
                href="/checkout"
                className="btn-primary block text-center px-6 sm:px-8 py-4 rounded-2xl font-bold text-sm shadow-md whitespace-nowrap"
              >
                {t.cart.checkout}
              </Link>
            ) : (
              <>
                <button
                  type="button"
                  onClick={() => setShowCheckoutGate(true)}
                  className="btn-primary w-full px-6 sm:px-8 py-4 rounded-2xl font-bold text-sm shadow-md whitespace-nowrap"
                >
                  {t.cart.checkout}
                </button>
                <GateModal
                  open={showCheckoutGate}
                  type="checkout"
                  returnTo="/checkout"
                  onClose={() => setShowCheckoutGate(false)}
                />
              </>
            )}
            <Link
              href="/products"
              className="block text-center text-sm text-gray-400 hover:text-gray-600 mt-3 transition-colors"
            >
              ← {t.cart.continueShopping}
            </Link>

            {/* Trust signals */}
            <div className="mt-5 pt-5 border-t border-gray-100 flex items-center justify-center gap-4">
              {["Secure", "Fast", "Easy Returns"].map((label) => (
                <span
                  key={label}
                  className="text-[10px] text-gray-400 font-medium"
                >
                  {label}
                </span>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
