import { useState, useEffect } from 'react';
import {
  createHardwareWallet,
  isHardwareWalletSupported,
  isWebHIDSupported,
  type HardwareWalletType,
  type HardwareWalletInfo,
  type HardwareWalletAccount,
  type HardwareWallet,
} from '../lib/hardware-wallet';

interface HardwareWalletConnectProps {
  onAccountSelected: (account: HardwareWalletAccount, wallet: HardwareWallet) => void;
  onCancel: () => void;
}

type ConnectionStep = 'select' | 'connecting' | 'accounts' | 'error';

export function HardwareWalletConnect({
  onAccountSelected,
  onCancel,
}: HardwareWalletConnectProps) {
  const [step, setStep] = useState<ConnectionStep>('select');
  const [selectedType, setSelectedType] = useState<HardwareWalletType | null>(null);
  const [wallet, setWallet] = useState<HardwareWallet | null>(null);
  const [walletInfo, setWalletInfo] = useState<HardwareWalletInfo | null>(null);
  const [accounts, setAccounts] = useState<HardwareWalletAccount[]>([]);
  const [error, setError] = useState<string>('');
  const [isSupported] = useState(isHardwareWalletSupported());

  const handleSelectWallet = async (type: HardwareWalletType) => {
    setSelectedType(type);
    setStep('connecting');
    setError('');

    try {
      const hw = createHardwareWallet(type);
      const info = await hw.connect();
      setWallet(hw);
      setWalletInfo(info);

      // Get accounts
      const accts = await hw.getAccounts(5);
      setAccounts(accts);
      setStep('accounts');
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Connection failed');
      setStep('error');
    }
  };

  const handleSelectAccount = (account: HardwareWalletAccount) => {
    if (wallet) {
      onAccountSelected(account, wallet);
    }
  };

  const handleRetry = () => {
    setStep('select');
    setError('');
    if (wallet) {
      wallet.disconnect().catch(() => {});
      setWallet(null);
    }
  };

  useEffect(() => {
    return () => {
      // Cleanup on unmount
      if (wallet) {
        wallet.disconnect().catch(() => {});
      }
    };
  }, [wallet]);

  if (!isSupported) {
    return (
      <div className="fixed inset-0 z-50 bg-black/80 flex items-center justify-center p-4">
        <div className="bg-slate-800 rounded-xl p-6 max-w-md w-full">
          <h2 className="text-xl font-bold mb-4">Hardware Wallet Not Supported</h2>
          <p className="text-slate-400 mb-4">
            Your browser doesn't support hardware wallet connections. Please use a
            desktop browser like Chrome, Edge, or Brave.
          </p>
          <button onClick={onCancel} className="w-full btn btn-secondary">
            Close
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="fixed inset-0 z-50 bg-black/80 flex items-center justify-center p-4">
      <div className="bg-slate-800 rounded-xl p-6 max-w-md w-full">
        {/* Header */}
        <div className="flex items-center justify-between mb-6">
          <h2 className="text-xl font-bold">Connect Hardware Wallet</h2>
          <button
            onClick={onCancel}
            className="p-2 hover:bg-slate-700 rounded-lg transition-colors"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>

        {/* Step: Select Wallet Type */}
        {step === 'select' && (
          <div className="space-y-4">
            <p className="text-slate-400 text-sm mb-4">
              Select your hardware wallet to connect securely.
            </p>

            {/* Ledger */}
            <button
              onClick={() => handleSelectWallet('ledger')}
              disabled={!isWebHIDSupported()}
              className="w-full flex items-center gap-4 p-4 bg-slate-700 hover:bg-slate-600 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <div className="w-12 h-12 bg-black rounded-lg flex items-center justify-center">
                <svg className="w-8 h-8" viewBox="0 0 24 24" fill="white">
                  <path d="M0 6h8v2H2v10h6v2H0V6zm16 0h8v14h-10v-2h8V8h-6V6z" />
                </svg>
              </div>
              <div className="text-left flex-1">
                <div className="font-semibold">Ledger</div>
                <div className="text-sm text-slate-400">Nano S, S Plus, X</div>
              </div>
              {!isWebHIDSupported() && (
                <span className="text-xs text-amber-400">WebHID not supported</span>
              )}
            </button>

            {/* Trezor */}
            <button
              onClick={() => handleSelectWallet('trezor')}
              className="w-full flex items-center gap-4 p-4 bg-slate-700 hover:bg-slate-600 rounded-lg transition-colors"
            >
              <div className="w-12 h-12 bg-green-900 rounded-lg flex items-center justify-center">
                <svg className="w-8 h-8" viewBox="0 0 24 24" fill="white">
                  <path d="M12 1L3 5v6c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V5l-9-4z" />
                </svg>
              </div>
              <div className="text-left flex-1">
                <div className="font-semibold">Trezor</div>
                <div className="text-sm text-slate-400">Model T, Model One</div>
              </div>
            </button>

            <p className="text-xs text-slate-500 mt-4">
              Your private keys never leave your hardware wallet. Only the
              Ed25519 signature is requested.
            </p>
          </div>
        )}

        {/* Step: Connecting */}
        {step === 'connecting' && (
          <div className="text-center py-8">
            <div className="animate-spin w-12 h-12 border-4 border-synor-400 border-t-transparent rounded-full mx-auto mb-4" />
            <p className="text-lg font-medium mb-2">Connecting to {selectedType}...</p>
            <p className="text-sm text-slate-400">
              {selectedType === 'ledger'
                ? 'Please connect your Ledger and open the Synor app.'
                : 'Please follow the instructions in the Trezor popup.'}
            </p>
          </div>
        )}

        {/* Step: Select Account */}
        {step === 'accounts' && (
          <div>
            {walletInfo && (
              <div className="flex items-center gap-3 p-3 bg-green-900/30 border border-green-700/50 rounded-lg mb-4">
                <div className="w-2 h-2 bg-green-400 rounded-full" />
                <span className="text-green-300 text-sm">
                  Connected: {walletInfo.model}
                  {walletInfo.firmwareVersion && ` (v${walletInfo.firmwareVersion})`}
                </span>
              </div>
            )}

            <p className="text-sm text-slate-400 mb-4">
              Select an account to use with Synor Wallet:
            </p>

            <div className="space-y-2 max-h-64 overflow-y-auto">
              {accounts.map((account, index) => (
                <button
                  key={account.path}
                  onClick={() => handleSelectAccount(account)}
                  className="w-full flex items-center gap-3 p-3 bg-slate-700 hover:bg-slate-600 rounded-lg transition-colors text-left"
                >
                  <div className="w-8 h-8 bg-synor-500 rounded-full flex items-center justify-center text-sm font-bold">
                    {index + 1}
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="font-mono text-sm truncate">{account.address}</div>
                    <div className="text-xs text-slate-400">{account.path}</div>
                  </div>
                </button>
              ))}
            </div>

            <button
              onClick={handleRetry}
              className="w-full btn btn-secondary mt-4"
            >
              Use Different Wallet
            </button>
          </div>
        )}

        {/* Step: Error */}
        {step === 'error' && (
          <div className="text-center py-4">
            <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-red-900/50 flex items-center justify-center">
              <svg className="w-8 h-8 text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </div>
            <h3 className="text-lg font-semibold mb-2">Connection Failed</h3>
            <p className="text-slate-400 text-sm mb-4">{error}</p>
            <div className="space-y-2">
              <button onClick={handleRetry} className="w-full btn btn-primary">
                Try Again
              </button>
              <button onClick={onCancel} className="w-full btn btn-secondary">
                Cancel
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
