import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Check, Tag, X } from "lucide-react";
import { promoService, type PromoApplyResult } from "@/services/api/promo";
import type { PurchaseContext } from "@/types";

export function PromoCodeInput({
  ctx, subtotal, applied, onApply, onRemove,
}: {
  ctx: PurchaseContext;
  subtotal: number;
  applied: PromoApplyResult | null;
  onApply: (r: PromoApplyResult) => void;
  onRemove: () => void;
}) {
  const [code, setCode] = useState("");
  const [loading, setLoading] = useState(false);

  async function apply() {
    if (!code.trim()) return;
    setLoading(true);
    const r = await promoService.apply(code.trim(), ctx, subtotal);
    setLoading(false);
    onApply(r);
  }

  if (applied?.ok) {
    return (
      <div className="flex items-center gap-2 rounded-md border border-success/40 bg-success/10 px-3 py-2 text-sm">
        <Check className="h-4 w-4 text-success" />
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2"><Badge variant="outline" className="border-success/40 text-success">{applied.code.code}</Badge>{applied.message && <span className="truncate text-xs text-muted-foreground">{applied.message}</span>}</div>
          <div className="text-xs text-muted-foreground">−${applied.discountAmount.toFixed(2)} discount applied</div>
        </div>
        <Button size="sm" variant="ghost" onClick={() => { setCode(""); onRemove(); }}><X className="h-4 w-4" /></Button>
      </div>
    );
  }

  return (
    <div className="space-y-2">
      <div className="flex gap-2">
        <div className="relative flex-1">
          <Tag className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input value={code} onChange={(e) => setCode(e.target.value.toUpperCase())} placeholder="Promo code" className="pl-9 uppercase" onKeyDown={(e) => e.key === "Enter" && apply()} />
        </div>
        <Button type="button" variant="outline" onClick={apply} disabled={loading || !code.trim()}>{loading ? "Checking…" : "Apply"}</Button>
      </div>
      {applied && !applied.ok && <p className="text-xs text-destructive">{applied.message}</p>}
    </div>
  );
}