import { useState } from 'react';
import { Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { satsToMsat } from '../format';
import { CopyField } from '../CopyField';
import { useWalletOperations } from '../useWalletData';

// Create a BOLT11 invoice. Receiving needs no key material, so this works while the wallet is locked.
//
// The amount is entered in sats and converted with satsToMsat, which appends three zeros to the digit
// string rather than multiplying — the request field is a msat STRING and must stay one.

type CreateInvoiceDialogProps = { open: boolean; onOpenChange: (open: boolean) => void; walletId: number };

export const CreateInvoiceDialog = ({ open, onOpenChange, walletId }: CreateInvoiceDialogProps) => {
  const { createInvoice } = useWalletOperations(walletId);
  const [amountSats, setAmountSats] = useState('');
  const [memo, setMemo] = useState('');
  const [expiryMinutes, setExpiryMinutes] = useState('60');
  const [created, setCreated] = useState<string | null>(null);

  const close = () => {
    setAmountSats('');
    setMemo('');
    setExpiryMinutes('60');
    setCreated(null);
    onOpenChange(false);
  };

  const submit = async (ev: React.FormEvent) => {
    ev.preventDefault();
    const sats = Number(amountSats);
    const result = await createInvoice.mutateAsync({
      // Omitted entirely for a zero-amount invoice, which is a legitimate "payer decides" request.
      amountMsat: amountSats && Number.isFinite(sats) && sats > 0 ? satsToMsat(sats) : undefined,
      memo: memo.trim() || undefined,
      expirySeconds: Number(expiryMinutes) > 0 ? Number(expiryMinutes) * 60 : undefined,
    });
    setCreated(result.invoice.bolt11);
  };

  return (
    <Dialog open={open} onOpenChange={(next) => (next ? onOpenChange(true) : close())}>
      <DialogContent className="max-w-md">
        {created ? (
          <>
            <DialogHeader>
              <DialogTitle>Invoice created</DialogTitle>
              <DialogDescription>Send this to whoever is paying you.</DialogDescription>
            </DialogHeader>
            <CopyField value={created} wrap label="BOLT11" />
            <DialogFooter>
              <Button onClick={close}>Done</Button>
            </DialogFooter>
          </>
        ) : (
          <form onSubmit={submit}>
            <DialogHeader>
              <DialogTitle>New invoice</DialogTitle>
              <DialogDescription>Leave the amount blank to let the payer choose.</DialogDescription>
            </DialogHeader>

            <div className="mt-4 space-y-4">
              <div className="space-y-1.5">
                <Label htmlFor="wallet-inv-amount">Amount (sats)</Label>
                <Input
                  id="wallet-inv-amount"
                  type="number"
                  min={0}
                  value={amountSats}
                  placeholder="any amount"
                  onChange={(ev) => setAmountSats(ev.target.value)}
                />
              </div>
              <div className="space-y-1.5">
                <Label htmlFor="wallet-inv-memo">Description</Label>
                <Input
                  id="wallet-inv-memo"
                  value={memo}
                  placeholder="what this is for"
                  onChange={(ev) => setMemo(ev.target.value)}
                />
              </div>
              <div className="space-y-1.5">
                <Label htmlFor="wallet-inv-expiry">Expires in (minutes)</Label>
                <Input
                  id="wallet-inv-expiry"
                  type="number"
                  min={1}
                  value={expiryMinutes}
                  onChange={(ev) => setExpiryMinutes(ev.target.value)}
                  className="w-32"
                />
              </div>
            </div>

            <DialogFooter className="mt-6">
              <Button type="button" variant="ghost" onClick={close}>
                Cancel
              </Button>
              <Button type="submit" disabled={createInvoice.isPending}>
                {createInvoice.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                Create
              </Button>
            </DialogFooter>
          </form>
        )}
      </DialogContent>
    </Dialog>
  );
};
