import { useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { Gift } from "lucide-react";
import { toast } from "sonner";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { redeemGiftCard } from "@/lib/gift-cards.functions";
import { formatNaira } from "@/lib/format";

/** Users redeem a Billsline gift card code to instantly top up their wallet. */
export function GiftCardRedeem() {
  const [code, setCode] = useState("");
  const qc = useQueryClient();
  const redeem = useServerFn(redeemGiftCard);

  const m = useMutation({
    mutationFn: (c: string) => redeem({ data: { code: c } }),
    onSuccess: (res) => {
      setCode("");
      toast.success(`Gift card redeemed — ${formatNaira(res.amount)} added to your wallet`);
      void qc.invalidateQueries({ queryKey: ["wallet"] });
      void qc.invalidateQueries({ queryKey: ["home-insights"] });
      void qc.invalidateQueries({ queryKey: ["transactions"] });
    },
    onError: (e: Error) => toast.error(e.message),
  });

  return (
    <div className="rounded-2xl bg-card p-4 shadow-card ring-1 ring-border/50">
      <div className="flex items-center gap-2">
        <span className="grid h-9 w-9 place-items-center rounded-xl bg-gradient-to-br from-fuchsia-500/20 to-pink-500/5 text-fuchsia-600">
          <Gift className="h-4.5 w-4.5" />
        </span>
        <div>
          <h3 className="text-sm font-bold">Billsline gift card</h3>
          <p className="text-xs text-muted-foreground">Enter a code to fund your wallet instantly.</p>
        </div>
      </div>
      <div className="mt-3 flex gap-2">
        <Input
          value={code}
          onChange={(e) => setCode(e.target.value.toUpperCase())}
          placeholder="BL-XXXX-XXXX-XXXX"
          className="font-mono tracking-wider"
        />
        <Button disabled={code.trim().length < 6 || m.isPending} onClick={() => m.mutate(code.trim())}>
          {m.isPending ? "Checking…" : "Redeem"}
        </Button>
      </div>
    </div>
  );
}
