import { useState } from 'react';
import { Lock, LockOpen, ShieldCheck } from 'lucide-react';
import { formatCountdown } from './format';
import { useLockCountdown } from './useLockCountdown';
import { useLockActions, useWalletConfig } from './useWalletData';
import { UnlockDialog } from './dialogs/UnlockDialog';

// The lock indicator. Locked is the resting state and reads as reassurance, not as an error — a watch-only
// wallet with no key material in memory is the whole point of the design, so it is never styled as a
// warning and never blocks the screen behind it.
//
// The countdown ticks locally (useLockCountdown) and flips to locked at zero without waiting for the poll.

type LockBadgeProps = {
  walletId: number | null;
  walletName: string;
  /** Compact drops the action button — for the panel header, where there is no room. */
  compact?: boolean;
};

export const LockBadge = ({ walletId, walletName, compact = false }: LockBadgeProps) => {
  const { hasSeed, unlocked, secondsRemaining, isLoading } = useLockCountdown(walletId);
  const { config } = useWalletConfig();
  const { lock } = useLockActions(walletId);
  const [unlockOpen, setUnlockOpen] = useState(false);

  // A wallet with no seed — a remote node, a custodial account — has nothing to lock. Showing it a
  // padlock would imply a protection it does not have.
  if (walletId == null || hasSeed === false) {
    if (isLoading || hasSeed == null) return null;
    return (
      <span className="flex items-center gap-1 text-[10px] text-muted-foreground">
        <ShieldCheck className="h-3 w-3" />
        no seed held
      </span>
    );
  }

  if (hasSeed == null) return null;

  return (
    <>
      <div className="flex items-center gap-2">
        <span
          className={`flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10px] font-medium tabular-nums ${
            unlocked ? 'bg-emerald-500/10 text-emerald-600' : 'bg-muted text-muted-foreground'
          }`}
          title={
            unlocked
              ? 'The seed is decrypted in the sidecar until this countdown ends'
              : 'Locked — balances and history still work; only signing needs the passphrase'
          }
        >
          {unlocked ? <LockOpen className="h-3 w-3" /> : <Lock className="h-3 w-3" />}
          {unlocked ? formatCountdown(secondsRemaining) : 'locked'}
        </span>

        {!compact &&
          (unlocked ? (
            <button
              type="button"
              onClick={() => lock.mutate()}
              disabled={lock.isPending}
              className="text-[10px] font-medium text-primary hover:underline"
            >
              lock now
            </button>
          ) : (
            <button
              type="button"
              onClick={() => setUnlockOpen(true)}
              className="text-[10px] font-medium text-primary hover:underline"
            >
              unlock
            </button>
          ))}
      </div>

      {unlockOpen && (
        <UnlockDialog
          open={unlockOpen}
          onOpenChange={setUnlockOpen}
          walletId={walletId}
          walletName={walletName}
          maxTtlSec={config?.unlockTtlSec ?? 300}
        />
      )}
    </>
  );
};

/**
 * The inline "you need to unlock for this" prompt, used by the signing surfaces only. Renders its children
 * disabled-in-place rather than replacing the screen, so you can still read the form you are about to
 * submit while the wallet is locked.
 */
type UnlockPromptProps = { walletId: number; walletName: string; className?: string };

export const UnlockPrompt = ({ walletId, walletName, className = '' }: UnlockPromptProps) => {
  const { config } = useWalletConfig();
  const [open, setOpen] = useState(false);

  return (
    <>
      <div
        className={`flex items-center gap-3 rounded-lg border border-border bg-muted/40 px-3 py-2 text-xs ${className}`}
      >
        <Lock className="h-4 w-4 shrink-0 text-muted-foreground" />
        <span className="flex-1 text-muted-foreground">
          This wallet is locked. Signing needs the passphrase — everything else on this screen already works.
        </span>
        <button
          type="button"
          onClick={() => setOpen(true)}
          className="shrink-0 rounded-md bg-primary px-2.5 py-1 text-xs font-medium text-primary-foreground hover:bg-primary/90"
        >
          Unlock
        </button>
      </div>

      {open && (
        <UnlockDialog
          open={open}
          onOpenChange={setOpen}
          walletId={walletId}
          walletName={walletName}
          maxTtlSec={config?.unlockTtlSec ?? 300}
        />
      )}
    </>
  );
};
