"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import {
  RiStarFill,
  RiSubtractLine,
  RiAddLine,
  RiShoppingCartLine,
  RiHeartLine,
  RiHeartFill,
  RiExchangeLine,
  RiShieldCheckLine,
  RiAwardLine,
  RiTruckLine,
} from "@remixicon/react";
import { useProduct } from "@/app/(users)/product/[slug]/product-page-client";
import { addToCart } from "@/lib/actions/cart";
import { toggleWishlist } from "@/lib/actions/wishlist";

const MAX_QTY = 10;

export default function ProductDetails() {
  const product = useProduct();
  const router = useRouter();
  const [quantity, setQuantity] = useState(1);
  const [wishlisted, setWishlisted] = useState(false);
  const [busy, setBusy] = useState<"add" | "buy" | "wish" | null>(null);
  const [notice, setNotice] = useState<{ ok: boolean; text: string } | null>(
    null,
  );

  // Cap the stepper at both the UI ceiling and available stock, so a shopper
  // can never select a quantity the server would reject.
  const { inventory: stockInventory } = product;
  const maxQuantity = stockInventory.trackInventory
    ? Math.min(MAX_QTY, stockInventory.stockQuantity)
    : MAX_QTY;

  const decrement = () => setQuantity((q) => Math.max(1, q - 1));
  const increment = () => setQuantity((q) => Math.min(maxQuantity, q + 1));

  async function handleAddToCart() {
    setBusy("add");
    setNotice(null);
    const res = await addToCart({ productId: product.id, quantity });
    setBusy(null);
    if (res.ok) {
      setNotice({ ok: true, text: res.message ?? "Added to cart." });
    } else {
      setNotice({ ok: false, text: res.error });
    }
  }

  async function handleBuyNow() {
    setBusy("buy");
    setNotice(null);
    const res = await addToCart({ productId: product.id, quantity });
    setBusy(null);
    if (res.ok) {
      router.push("/checkout");
    } else {
      setNotice({ ok: false, text: res.error });
    }
  }

  async function handleToggleWishlist() {
    setBusy("wish");
    setNotice(null);
    const res = await toggleWishlist(product.id);
    setBusy(null);
    if (res.ok) {
      setWishlisted(res.data?.wishlisted ?? !wishlisted);
      setNotice({ ok: true, text: res.message ?? "" });
    } else {
      setNotice({ ok: false, text: res.error });
    }
  }

  const { pricing, reviews } = product;
  const hasDiscount =
    pricing.compareAtPrice && pricing.compareAtPrice > pricing.sellingPrice;
  const discountPct = hasDiscount
    ? Math.round(
        ((pricing.compareAtPrice! - pricing.sellingPrice) /
          pricing.compareAtPrice!) *
          100,
      )
    : 0;
  const savings = hasDiscount
    ? pricing.compareAtPrice! - pricing.sellingPrice
    : 0;

  return (
    <div className="lg:col-span-5 flex flex-col gap-8">
      <div>
        <div className="flex items-center justify-between mb-3">
          {product.brand && (
            <span className="font-label-md text-label-md text-primary bg-primary-fixed px-3 py-1 rounded-full">
              {product.brand.name}
            </span>
          )}
          <span className="font-label-sm text-label-sm text-on-surface-variant">
            SKU: {product.sku}
          </span>
        </div>

        <h1 className="text-2xl font-bold mb-3">{product.name}</h1>

        <div className="flex items-center gap-3 mb-6">
          <div className="flex items-center gap-0.5 text-primary">
            {[1, 2, 3, 4, 5].map((star) => (
              <RiStarFill
                key={star}
                className={`h-4 w-4 ${
                  star <= Math.round(reviews.average)
                    ? "fill-current"
                    : "text-outline"
                }`}
              />
            ))}
          </div>
          <span className="font-label-md text-label-md text-on-surface">
            {reviews.average}
          </span>
          <span className="font-body-sm text-body-sm text-on-surface-variant">
            ({reviews.count.toLocaleString()} reviews)
          </span>
        </div>

        <div className="flex items-baseline gap-3 mb-3">
          <span className="font-display-lg text-2xl font-bold">
            <span>&#x09F3;</span>
            {pricing.sellingPrice.toLocaleString()}
          </span>
          {hasDiscount && (
            <>
              <span className="font-body-lg text-body-lg text-on-surface-variant line-through">
                <span>&#x09F3;</span>
                {pricing.compareAtPrice!.toLocaleString()}
              </span>
              <span className="bg-error text-white px-2 py-1 rounded font-label-sm text-label-sm uppercase">
                {discountPct}% off
              </span>
            </>
          )}
        </div>
        {hasDiscount && (
          <p className="font-body-sm text-body-sm text-on-surface-variant mb-4">
            You save <span>&#x09F3;</span>
            {savings.toLocaleString()} with this offer
          </p>
        )}

        <p className="flex items-center gap-2 text-on-surface font-label-md text-label-md">
          <span className="relative flex h-2 w-2">
            <span
              className={`absolute inline-flex h-full w-full animate-ping rounded-full opacity-75 ${
                stockInventory.inStock ? "bg-green-500" : "bg-red-500"
              }`}
            />
            <span
              className={`relative inline-flex h-2 w-2 rounded-full ${
                stockInventory.inStock ? "bg-green-500" : "bg-red-500"
              }`}
            />
          </span>
          {stockInventory.inStock ? "In Stock & Ready to Ship" : "Out of Stock"}
        </p>
      </div>

      <div className="flex flex-col gap-3">
        <div className="flex items-center gap-4">
          <div className="flex items-center border border-outline-variant rounded-lg p-1 bg-surface">
            <button
              type="button"
              onClick={decrement}
              disabled={quantity <= 1}
              aria-label="Decrease quantity"
              className="w-10 h-10 flex items-center justify-center hover:bg-surface-container-high rounded transition-colors disabled:opacity-30 disabled:hover:bg-transparent"
            >
              <RiSubtractLine />
            </button>
            <input
              className="w-12 text-center border-none bg-transparent font-body-md focus:ring-0"
              type="number"
              value={quantity}
              readOnly
              aria-label="Quantity"
            />
            <button
              type="button"
              onClick={increment}
              disabled={quantity >= maxQuantity || !stockInventory.inStock}
              aria-label="Increase quantity"
              className="w-10 h-10 flex items-center justify-center hover:bg-surface-container-high rounded transition-colors disabled:opacity-30 disabled:hover:bg-transparent"
            >
              <RiAddLine />
            </button>
          </div>
          {stockInventory.trackInventory &&
            stockInventory.stockQuantity > 0 &&
            stockInventory.stockQuantity < MAX_QTY && (
              <span className="text-sm text-amber-600">
                Only {stockInventory.stockQuantity} in stock
              </span>
            )}
          <button
            type="button"
            disabled={!stockInventory.inStock || busy !== null}
            onClick={handleAddToCart}
            className="flex-1 bg-primary text-white h-12 rounded-lg font-label-md hover:opacity-90 transition-all flex items-center justify-center gap-2 disabled:opacity-50"
          >
            <RiShoppingCartLine />{" "}
            {busy === "add" ? "Adding..." : "Add to Cart"}
          </button>
        </div>

        <button
          type="button"
          disabled={!stockInventory.inStock || busy !== null}
          onClick={handleBuyNow}
          className="w-full border-2 border-primary text-primary h-12 rounded-lg font-label-md hover:bg-primary hover:text-white transition-all disabled:opacity-50"
        >
          {busy === "buy" ? "Redirecting..." : "Buy It Now"}
        </button>

        {notice && (
          <p
            role="alert"
            className={`text-sm ${notice.ok ? "text-green-600" : "text-red-600"}`}
          >
            {notice.text}
          </p>
        )}

        <div className="flex items-center justify-between pt-2">
          <button
            type="button"
            onClick={handleToggleWishlist}
            disabled={busy !== null}
            aria-pressed={wishlisted}
            className={`flex items-center gap-2 font-label-sm text-label-sm transition-colors ${
              wishlisted
                ? "text-primary"
                : "text-on-surface-variant hover:text-primary"
            }`}
          >
            {wishlisted ? <RiHeartFill /> : <RiHeartLine />}
            {wishlisted ? "Wishlisted" : "Add to Wishlist"}
          </button>
          <button
            type="button"
            className="flex items-center gap-2 text-on-surface-variant hover:text-primary font-label-sm text-label-sm transition-colors"
          >
            <RiExchangeLine />
            Compare
          </button>
        </div>
      </div>

      <div className="grid grid-cols-3 border-t border-outline-variant pt-8">
        <div className="flex flex-col items-center text-center gap-2 px-2 border-r border-outline-variant">
          <RiShieldCheckLine className="text-primary text-3xl" />
          <span className="font-label-sm text-label-sm">Secure Payment</span>
        </div>
        <div className="flex flex-col items-center text-center gap-2 px-2 border-r border-outline-variant">
          <RiAwardLine className="text-primary text-3xl" />
          <span className="font-label-sm text-label-sm">Official Warranty</span>
        </div>
        <div className="flex flex-col items-center text-center gap-2 px-2">
          <RiTruckLine className="text-primary text-3xl" />
          <span className="font-label-sm text-label-sm">Fast Delivery</span>
        </div>
      </div>
    </div>
  );
}
