"use client";

import { useState } from "react";
import Image from "next/image";
import { ShoppingBag } from "lucide-react";
import { minimumPrice, type CatalogProduct } from "@/data/catalog";
import { formatPrice } from "@/data/category-showcases";
import { useDemoStore } from "./demo-store";
import { ProductGallery } from "@/components/product/product-gallery";
import { QuantityControl } from "@/components/commerce/quantity-control";
import Link from "next/link";
import { productHref } from "@/lib/products";

export function ProductOptions({ product, initialVariantId, details = false, onSelectionChange, onViewDetails, onAdded }: { product: CatalogProduct; initialVariantId?: string; details?: boolean; onViewDetails?: () => void; onSelectionChange?: (id?: string) => void; onAdded: () => void }) {
  const initial = product.variants.find((variant) => variant.id === initialVariantId);
  const [color, setColor] = useState(initial?.color ?? product.variants[0].color);
  const [size, setSize] = useState(initial?.size ?? "");
  const [quantity, setQuantity] = useState(1);
  const { addItem, cart } = useDemoStore();
  const colors = [...new Map(product.variants.map((variant) => [variant.color, variant])).values()];
  const variants = product.variants.filter((variant) => variant.color === color);
  const selected = variants.find((variant) => variant.size === size);
  const image = (selected ?? variants[0]).images[0];
  const price = selected?.price ?? Math.min(...variants.map((variant) => variant.price));
  const quantityInBag = cart.find((line) => line.variantId === selected?.id)?.quantity ?? 0;
  const available = !!selected && selected.stock > quantityInBag;
  return (
    <div className={`product-options ${details ? "full-product-options" : ""}`}>
      {details ? <ProductGallery key={(selected ?? variants[0]).id} images={(selected ?? variants[0]).images} name={`${product.name}, ${color}`} /> : <div className="product-options-image"><Image src={image} alt={`${product.name}, ${color}`} fill sizes="(max-width: 600px) 85vw, 350px" className="category-product-image" /></div>}
      <div className="product-options-copy"><p className="eyebrow">{product.group} / {product.categoryName}</p>{details ? <h1>{product.name}</h1> : <h3>{product.name}</h3>}<p className="product-options-price" aria-live="polite">{!selected && product.variants.some((variant) => variant.price !== minimumPrice(product)) && <small>From </small>}{formatPrice(price)}</p><p className="product-options-description">{product.description}</p>
        <fieldset><legend>Colour: <strong>{color}</strong></legend><div className="product-colors">{colors.map((variant) => <button type="button" key={variant.color} onClick={() => { setColor(variant.color); setSize(""); setQuantity(1); onSelectionChange?.(); }} aria-label={`Select ${variant.color}`} aria-pressed={color === variant.color} style={{ "--swatch": variant.colorHex } as React.CSSProperties}><span /></button>)}</div></fieldset>
        <fieldset><legend>Select size</legend><div className="product-sizes">{variants.map((variant) => <button type="button" key={variant.id} onClick={() => { setSize(variant.size); setQuantity(1); onSelectionChange?.(variant.id); }} disabled={variant.stock === 0} aria-pressed={size === variant.size} aria-label={`${variant.size}${variant.stock === 0 ? ", sold out" : ""}`}>{variant.size}</button>)}</div></fieldset>
        <p className="variant-availability" aria-live="polite">{!selected ? "Choose a size to continue." : available ? `${selected.stock - quantityInBag} available` : "This selection is unavailable."}</p>
        {details && selected && <p className="product-sku">SKU: {selected.sku}</p>}
        {details && selected && <div className="product-detail-quantity"><span>Quantity</span><QuantityControl value={quantity} stock={Math.max(1, selected.stock - quantityInBag)} label={product.name} onChange={setQuantity} /></div>}
        <button type="button" className="button button-primary add-variant-button" disabled={!available || !!selected && quantity > selected.stock - quantityInBag} onClick={() => { if (selected && addItem(product.id, selected.id, details ? quantity : 1)) onAdded(); }}><ShoppingBag size={16} /> Add to bag {selected ? `— ${formatPrice(selected.price * (details ? quantity : 1))}` : ""}</button>
        {!details && <Link href={productHref(product.id, selected?.id)} onClick={onViewDetails} className="text-link">View full product details</Link>}
      </div>
    </div>
  );
}
