"use client";

import { useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import { useCart } from "@/lib/cart-context";
import { formatPaise } from "@/lib/format";
import { parseImages } from "@/lib/types";
import { whatsappLink } from "@/lib/site";
import { effectiveUnitPrice, type BulkTier } from "@/lib/pricing";
import WishlistButton from "@/components/WishlistButton";

type Variant = { id: string; name: string; priceDelta: number; stock: number };

export default function AddToCartForm({
  productId,
  slug,
  name,
  images,
  basePrice,
  salePrice,
  categoryDiscountPercent,
  bulkTiers,
  minOrderQty,
  personalizable,
  variants,
  stock,
  salesEnabled,
  pausedMessage,
}: {
  productId: string;
  slug: string;
  name: string;
  images: string;
  basePrice: number;
  salePrice?: number | null;
  categoryDiscountPercent?: number | null;
  bulkTiers: BulkTier[];
  minOrderQty: number;
  personalizable: boolean;
  variants: Variant[];
  stock: number | null;
  salesEnabled: boolean;
  pausedMessage: string;
}) {
  const { addItem } = useCart();
  const router = useRouter();
  const [variantId, setVariantId] = useState(variants[0]?.id ?? "");
  const [quantityInput, setQuantityInput] = useState(String(minOrderQty || 1));
  const [personalization, setPersonalization] = useState("");
  const [added, setAdded] = useState(false);

  const selectedVariant = variants.find((v) => v.id === variantId);
  const quantity = Math.max(1, Math.round(Number(quantityInput)) || 0);
  const { price: discountedBase, label: discountLabel } = effectiveUnitPrice(
    { basePrice, salePrice: salePrice ?? null, category: { discountPercent: categoryDiscountPercent ?? null } },
    quantity,
    bulkTiers
  );
  const onSale = discountLabel !== null || (salePrice != null && salePrice < basePrice);
  const unitPrice = discountedBase + (selectedVariant?.priceDelta ?? 0);
  const outOfStock = variants.length > 0 ? (selectedVariant ? selectedVariant.stock <= 0 : false) : stock !== null && stock <= 0;
  const image = useMemo(() => parseImages(images)[0], [images]);
  const wishlistItem = { productId, name, slug, image, basePrice: salePrice != null && salePrice < basePrice ? salePrice : basePrice, minOrderQty };

  function handleAdd() {
    const qty = Math.max(minOrderQty || 1, quantity);
    setQuantityInput(String(qty));
    const { price: finalBase } = effectiveUnitPrice(
      { basePrice, salePrice: salePrice ?? null, category: { discountPercent: categoryDiscountPercent ?? null } },
      qty,
      bulkTiers
    );
    addItem({
      productId,
      variantId: selectedVariant?.id,
      name,
      variantName: selectedVariant?.name,
      slug,
      image,
      unitPrice: finalBase + (selectedVariant?.priceDelta ?? 0),
      quantity: qty,
      minOrderQty: minOrderQty || 1,
      personalization: personalization.trim() || undefined,
    });
    setAdded(true);
    setTimeout(() => setAdded(false), 2000);
  }

  return (
    <div className="space-y-5">
      <div className="flex items-baseline gap-2">
        <div className="text-2xl font-semibold text-rose-800">{formatPaise(unitPrice)}</div>
        {onSale && <div className="text-base text-stone-400 line-through">{formatPaise(basePrice + (selectedVariant?.priceDelta ?? 0))}</div>}
      </div>
      {discountLabel && <p className="text-xs font-medium text-emerald-700">{discountLabel} applied — {formatPaise(unitPrice * quantity)} total for {quantity}</p>}

      {outOfStock ? (
        <p className="text-sm font-medium text-red-600">Out of Stock</p>
      ) : (
        <p className="text-sm font-medium text-emerald-600">In Stock</p>
      )}
      <div className="flex items-center gap-1.5 text-xs text-stone-500">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" className="h-4 w-4 text-emerald-600">
          <path fillRule="evenodd" d="M8.603 3.799A4.49 4.49 0 0112 2.25c1.357 0 2.573.6 3.397 1.549a4.49 4.49 0 013.498 1.307 4.491 4.491 0 011.307 3.497A4.49 4.49 0 0121.75 12a4.49 4.49 0 01-1.549 3.397 4.491 4.491 0 01-1.307 3.497 4.491 4.491 0 01-3.497 1.307A4.49 4.49 0 0112 21.75a4.49 4.49 0 01-3.397-1.549 4.49 4.49 0 01-3.498-1.306 4.491 4.491 0 01-1.307-3.498A4.49 4.49 0 012.25 12c0-1.357.6-2.573 1.549-3.397a4.49 4.49 0 011.307-3.497 4.49 4.49 0 013.497-1.307zm7.007 6.387a.75.75 0 10-1.22-.872l-3.236 4.53L9.53 12.22a.75.75 0 00-1.06 1.06l2.25 2.25a.75.75 0 001.14-.094l3.75-5.25z" clipRule="evenodd" />
        </svg>
        100% Genuine Products
      </div>

      {!salesEnabled ? (
        <div className="rounded-lg border border-rose-100 bg-rose-50/60 p-4">
          <p className="text-sm font-medium text-stone-700">Checkout is temporarily paused</p>
          <p className="mt-1 text-sm text-stone-600">{pausedMessage}</p>
          <a
            href={whatsappLink(`Hi! I'd like to order "${name}".`)}
            target="_blank"
            rel="noopener noreferrer"
            className="mt-3 inline-block rounded-md bg-emerald-500 px-5 py-2.5 text-sm font-semibold text-white hover:bg-emerald-600"
          >
            WhatsApp us
          </a>
        </div>
      ) : (
        <>
      {variants.length > 0 && (
        <div>
          <label className="text-sm font-medium text-stone-700">Option</label>
          <select
            value={variantId}
            onChange={(e) => setVariantId(e.target.value)}
            className="mt-1 block w-full rounded-md border border-stone-300 px-3 py-2 text-sm"
          >
            {variants.map((v) => (
              <option key={v.id} value={v.id} disabled={v.stock <= 0}>
                {v.name} {v.stock <= 0 ? "(out of stock)" : v.priceDelta ? `(+${formatPaise(v.priceDelta)})` : ""}
              </option>
            ))}
          </select>
        </div>
      )}

      {personalizable && (
        <div>
          <label className="text-sm font-medium text-stone-700">Personalize (name / initials / message)</label>
          <input
            type="text"
            value={personalization}
            onChange={(e) => setPersonalization(e.target.value)}
            maxLength={60}
            placeholder="e.g. Priya & Arjun, 12 Feb 2027"
            className="mt-1 block w-full rounded-md border border-stone-300 px-3 py-2 text-sm"
          />
          <p className="mt-1.5 text-xs text-stone-500">
            Want a custom photo, logo, or design printed instead?{" "}
            <a
              href={whatsappLink(`Hi! I'd like a custom design for "${name}".`)}
              target="_blank"
              rel="noopener noreferrer"
              className="font-medium text-emerald-700 hover:underline"
            >
              WhatsApp us
            </a>{" "}
            and we&apos;ll sort it out with you directly.
          </p>
        </div>
      )}

      <div>
        <label className="text-sm font-medium text-stone-700">Quantity</label>
        <input
          type="number"
          min={minOrderQty || 1}
          value={quantityInput}
          onChange={(e) => setQuantityInput(e.target.value)}
          onBlur={() => setQuantityInput(String(Math.max(minOrderQty || 1, Math.round(Number(quantityInput)) || 0)))}
          className="mt-1 block w-28 rounded-md border border-stone-300 px-3 py-2 text-sm"
        />
        {minOrderQty > 1 && <p className="mt-1 text-xs text-stone-500">Minimum order quantity: {minOrderQty}</p>}
        {variants.length === 0 && stock !== null && stock > 0 && stock <= 10 && (
          <p className="mt-1 text-xs text-amber-600">Only {stock} left in stock</p>
        )}
        {bulkTiers.length > 0 && (
          <div className="mt-1.5 space-y-0.5">
            {bulkTiers.map((t) => (
              <p key={t.minQty} className="text-xs text-stone-500">
                Buy {t.minQty}+ pieces and get {t.discountPercent}% off per piece
              </p>
            ))}
          </div>
        )}
      </div>

      <div className="flex gap-3">
        <WishlistButton item={wishlistItem} label="Wishlist" />
        <button
          onClick={handleAdd}
          disabled={outOfStock}
          className="flex-1 rounded-md bg-rose-700 py-3 text-sm font-semibold text-white hover:bg-rose-800 disabled:cursor-not-allowed disabled:bg-stone-300"
        >
          {outOfStock ? "Out of stock" : added ? "Added ✓" : "Add to cart"}
        </button>
      </div>
      <div className="flex gap-3">
        <button
          onClick={() => {
            handleAdd();
            router.push("/checkout");
          }}
          disabled={outOfStock}
          className="flex-1 rounded-md border border-rose-700 py-3 text-sm font-semibold text-rose-700 hover:bg-rose-50 disabled:cursor-not-allowed disabled:border-stone-300 disabled:text-stone-400"
        >
          Buy now
        </button>
      </div>
        </>
      )}
    </div>
  );
}
