import { useState } from 'react';
import { Eye, Loader2, TriangleAlert } 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 { useLockActions } from '../useWalletData';

// Show the recovery phrase again — the one path back to it after creation, and the reason the create-time
// modal can say "not without your passphrase" rather than "never".
//
// Two things live only in this component and nowhere else: the passphrase (cleared the moment the request
// settles) and the returned mnemonic (held in local state, dropped when the dialog closes). The mutation
// deliberately has no onSuccess cache write, so the phrase never enters React Query. No copy button, for
// the same reason as SeedBackupDialog.

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

export const ExportSeedDialog = ({ open, onOpenChange, walletId }: ExportSeedDialogProps) => {
  const { exportSeed } = useLockActions(walletId);
  // Never persisted: no localStorage, no sessionStorage, no React Query cache, no URL.
  const [passphrase, setPassphrase] = useState('');
  const [revealed, setRevealed] = useState<{ mnemonic: string; hasBip39Passphrase: boolean } | null>(null);

  const close = () => {
    setPassphrase('');
    setRevealed(null);
    onOpenChange(false);
  };

  const submit = async (ev: React.FormEvent) => {
    ev.preventDefault();
    if (!passphrase) return;
    try {
      setRevealed(await exportSeed.mutateAsync({ passphrase }));
    } finally {
      setPassphrase('');
    }
  };

  const words = revealed ? revealed.mnemonic.trim().split(/\s+/) : [];

  return (
    <Dialog open={open} onOpenChange={(next) => (next ? onOpenChange(true) : close())}>
      <DialogContent className="max-w-lg">
        {revealed ? (
          <>
            <DialogHeader>
              <DialogTitle className="flex items-center gap-2">
                <TriangleAlert className="h-5 w-5 text-amber-500" />
                Recovery phrase
              </DialogTitle>
              <DialogDescription>
                Anyone who reads these {words.length} words can spend this wallet. Close this as soon as you are done.
              </DialogDescription>
            </DialogHeader>

            <ol className="mt-2 grid grid-cols-3 gap-1.5 rounded-lg border border-amber-500/30 bg-amber-500/5 p-3 sm:grid-cols-4">
              {words.map((word, i) => (
                <li key={`${i}-${word}`} className="flex items-baseline gap-1.5 font-mono text-xs">
                  <span className="w-5 shrink-0 text-right tabular-nums text-muted-foreground">{i + 1}</span>
                  <span className="font-medium">{word}</span>
                </li>
              ))}
            </ol>

            {revealed.hasBip39Passphrase && (
              <p className="text-xs text-amber-600">
                This seed also has a BIP39 passphrase. The words alone will not restore the wallet — you need both.
              </p>
            )}

            <DialogFooter>
              <Button onClick={close}>Done</Button>
            </DialogFooter>
          </>
        ) : (
          <form onSubmit={submit}>
            <DialogHeader>
              <DialogTitle>Show recovery phrase</DialogTitle>
              <DialogDescription>
                The phrase is decrypted for display only. It is not stored by the browser and nothing is written
                anywhere on this side.
              </DialogDescription>
            </DialogHeader>

            <div className="mt-4 space-y-1.5">
              <Label htmlFor="wallet-export-pass">Passphrase</Label>
              {/* Controlled input → request body → cleared. Never written to any store. */}
              <Input
                id="wallet-export-pass"
                type="password"
                autoFocus
                autoComplete="off"
                value={passphrase}
                onChange={(ev) => setPassphrase(ev.target.value)}
              />
            </div>

            <DialogFooter className="mt-6">
              <Button type="button" variant="ghost" onClick={close}>
                Cancel
              </Button>
              <Button type="submit" disabled={!passphrase || exportSeed.isPending}>
                {exportSeed.isPending ? (
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                ) : (
                  <Eye className="mr-2 h-4 w-4" />
                )}
                Show
              </Button>
            </DialogFooter>
          </form>
        )}
      </DialogContent>
    </Dialog>
  );
};
