"use client";

import * as React from "react";
import { ShoppingCartIcon } from "lucide-react";

import { Example } from "@/components/design-system/example";
import { Money } from "@/components/medora/money";
import { UnitPicker, UnitQuantity, availableOf, type UnitProduct } from "@/components/medora/units";
import { Button } from "@/components/ui/button";
import { toast } from "@/components/ui/toast";

const panadol: UnitProduct = {
  name: "Panadol 500 mg",
  baseUnit: "tablet",
  stock: 340,
  units: [
    { name: "Tablet", size: 1, price: 5 },
    { name: "Strip", size: 10, price: 45 },
    { name: "Box", size: 100, price: 420 },
  ],
};

const augmentin: UnitProduct = {
  name: "Augmentin 625 mg",
  baseUnit: "tablet",
  stock: 18,
  units: [
    { name: "Tablet", size: 1, price: 8.5 },
    { name: "Strip", size: 14, price: 110 },
    { name: "Box", size: 28, price: 210 },
  ],
};

const amoxil: UnitProduct = {
  name: "Amoxil 500 mg",
  baseUnit: "capsule",
  stock: 126,
  units: [
    { name: "Capsule", size: 1, price: 15 },
    { name: "Strip", size: 10, price: 140 },
  ],
};

const benylin: UnitProduct = { name: "Benylin Cough Syrup 100 ml", baseUnit: "bottle", stock: 24, units: [{ name: "Bottle", size: 1, price: 320 }] };

function AddToCart({ product, initial }: { product: UnitProduct; initial: string }) {
  const [unit, setUnit] = React.useState(initial);
  const [qty, setQty] = React.useState(1);
  const u = product.units.find((x) => x.name === unit)!;
  return (
    <div className="space-y-3">
      <div className="flex items-baseline justify-between gap-2">
        <p className="text-sm font-semibold">{product.name}</p>
        <p className="text-xs text-muted-foreground tabular-nums">{product.stock.toLocaleString("en-US")} {product.baseUnit}s in stock</p>
      </div>
      <UnitPicker
        product={product}
        value={unit}
        onChange={(n) => {
          setUnit(n);
          const next = product.units.find((x) => x.name === n)!;
          setQty((q) => Math.max(1, Math.min(q, availableOf(product, next))));
        }}
      />
      <div className="flex flex-wrap items-center justify-between gap-3 border-t border-border pt-3">
        <UnitQuantity product={product} qty={qty} unit={unit} onChange={(n) => {
            setQty(n.qty);
            setUnit(n.unit);
          }}
        />
        <div className="flex items-center gap-3">
          <Money amount={u.price * qty} size="lg" />
          <Button onClick={() => toast.add({ title: "Added to cart", description: `${qty} × ${u.name} of ${product.name}.` })}>
            <ShoppingCartIcon data-icon="inline-start" />
            Add
          </Button>
        </div>
      </div>
    </div>
  );
}

function CartRow({ product, initialUnit, initialQty }: { product: UnitProduct; initialUnit: string; initialQty: number }) {
  const [s, setS] = React.useState({ unit: initialUnit, qty: initialQty });
  const u = product.units.find((x) => x.name === s.unit)!;
  return (
    <div className="flex items-center justify-between gap-3 py-3">
      <div className="min-w-0">
        <p className="truncate text-sm font-medium">{product.name}</p>
        <p className="text-xs text-muted-foreground tabular-nums">
          {u.price.toFixed(2)} per {u.name.toLowerCase()}
        </p>
      </div>
      <div className="flex items-start gap-3">
        <UnitQuantity product={product} qty={s.qty} unit={s.unit} onChange={setS} />
        <Money amount={u.price * s.qty} className="mt-1.5 w-24 justify-end font-semibold text-primary" />
      </div>
    </div>
  );
}

export function UnitsDemos() {
  return (
    <div className="space-y-4">
      <div className="grid gap-4 lg:grid-cols-2">
        <Example title="Choose a unit" description="Bigger packs show their per-tablet saving; arrow keys move between units">
          <AddToCart product={panadol} initial="Strip" />
        </Example>
        <Example title="Low stock" description="18 tablets left: the box (28) cannot be sold, one strip (14) can">
          <AddToCart product={augmentin} initial="Tablet" />
        </Example>
      </div>
      <Example title="Cart lines with units" description="Change the unit in the line; quantity is kept but clamped to stock. Single-unit products show the unit as text" bare>
        <div className="divide-y divide-border px-4">
          <CartRow product={panadol} initialUnit="Strip" initialQty={2} />
          <CartRow product={amoxil} initialUnit="Capsule" initialQty={21} />
          <CartRow product={benylin} initialUnit="Bottle" initialQty={1} />
        </div>
      </Example>
    </div>
  );
}
