import React, { useState } from 'react';
import { useShadeState } from '../useShadeState.js';
import { useShadeContext } from '../ShadeProvider.js';
import { WidgetShell } from './shared.js';
import { formatOobText } from './FingerprintGate.js';

export interface FingerprintCompareProps {
  /**
   * Optional callback invoked when the user clicks "I have verified" after
   * confirming a peer's fingerprint matches. The widget passes the
   * normalized fingerprint that was compared. Wire this to
   * `Shade.markPeerVerified(address)` in your app.
   */
  onVerified?: (fingerprint: string) => void | Promise<void>;
  /** Optional peer address to display alongside the OOB-copy text. */
  peerAddress?: string;
}

/**
 * FingerprintCompare — paste a fingerprint and check if it matches your own
 * (or, when wired with `onVerified`, manually accept a peer's fingerprint).
 *
 * V3.3: extended with "Copy OOB text" + "I have verified" actions so the
 * widget can drive `Shade.markPeerVerified` directly.
 */
export function FingerprintCompare(props: FingerprintCompareProps = {}): React.ReactElement {
  const { state } = useShadeState();
  const { theme } = useShadeContext();
  const [input, setInput] = useState('');
  const [copied, setCopied] = useState(false);

  const normalized = input.replace(/\s+/g, ' ').trim();
  const yourFp = state?.identity.fingerprint?.replace(/\s+/g, ' ').trim();
  const matches = normalized.length > 0 && yourFp !== undefined && normalized === yourFp;

  const copyOob = async () => {
    if (yourFp === undefined) return;
    const text = formatOobText(props.peerAddress ?? 'me', yourFp);
    if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText !== undefined) {
      await navigator.clipboard.writeText(text);
      setCopied(true);
      setTimeout(() => setCopied(false), 1500);
    }
  };

  const verify = async () => {
    if (normalized.length === 0) return;
    await props.onVerified?.(normalized);
  };

  return (
    <WidgetShell title="Verify fingerprint">
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        <textarea
          placeholder="Paste a 60-digit safety number to compare with your own identity"
          value={input}
          onChange={(e) => setInput(e.target.value)}
          rows={3}
          style={{
            width: '100%',
            background: theme.bg,
            border: `1px solid ${theme.border}`,
            borderRadius: 6,
            padding: 10,
            fontFamily: theme.fontMono,
            fontSize: 12,
            color: theme.text,
            resize: 'vertical',
            outline: 'none',
            boxSizing: 'border-box',
          }}
        />
        {normalized.length > 0 && (
          <div
            style={{
              padding: 10,
              borderRadius: 6,
              fontSize: 12,
              fontWeight: 600,
              border: `1px solid ${matches ? theme.success : theme.danger}`,
              background: matches ? 'rgba(34, 197, 94, 0.08)' : 'rgba(239, 68, 68, 0.08)',
              color: matches ? theme.success : theme.danger,
              textAlign: 'center',
            }}
          >
            {matches ? '✓ Matches your identity' : '✗ Does not match your identity'}
          </div>
        )}
        <div style={{ display: 'flex', gap: 8 }}>
          <button
            type="button"
            onClick={() => void copyOob()}
            disabled={yourFp === undefined}
            style={{
              flex: 1,
              background: 'transparent',
              color: theme.text,
              border: `1px solid ${theme.border}`,
              borderRadius: 6,
              padding: '6px 12px',
              fontFamily: theme.font,
              fontSize: 12,
              fontWeight: 600,
              cursor: yourFp === undefined ? 'not-allowed' : 'pointer',
              opacity: yourFp === undefined ? 0.5 : 1,
            }}
          >
            {copied ? 'Copied!' : 'Copy OOB text'}
          </button>
          {props.onVerified !== undefined && (
            <button
              type="button"
              onClick={() => void verify()}
              disabled={normalized.length === 0}
              style={{
                flex: 1,
                background: theme.accent,
                color: theme.bg,
                border: `1px solid ${theme.accent}`,
                borderRadius: 6,
                padding: '6px 12px',
                fontFamily: theme.font,
                fontSize: 12,
                fontWeight: 600,
                cursor: normalized.length === 0 ? 'not-allowed' : 'pointer',
                opacity: normalized.length === 0 ? 0.5 : 1,
              }}
            >
              I have verified
            </button>
          )}
        </div>
      </div>
    </WidgetShell>
  );
}
