import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useWalletStore } from '../store/wallet';
import { createSendTransaction, serializeTransaction } from '../lib/transaction';
import { getClient } from '../lib/rpc';
import { QRScanner } from '../components/QRScanner';
import { parsePaymentUri } from '../components/QRCode';

export default function SendPage() {
  const { address, keypair, balance, refreshBalance } = useWalletStore();
  const navigate = useNavigate();

  const [recipient, setRecipient] = useState('');
  const [amount, setAmount] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState<{ txId: string } | null>(null);
  const [showScanner, setShowScanner] = useState(false);

  const handleQRScan = (scannedText: string) => {
    setShowScanner(false);
    const parsed = parsePaymentUri(scannedText);
    if (parsed) {
      setRecipient(parsed.address);
      if (parsed.amount) {
        setAmount(parsed.amount);
      }
    } else if (scannedText.startsWith('synor:')) {
      // Plain address without parameters
      setRecipient(scannedText);
    } else {
      setError('Invalid QR code. Expected a Synor address.');
    }
  };

  const handleSend = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setSuccess(null);

    if (!address || !keypair) {
      setError('Wallet not unlocked');
      return;
    }

    // Validate recipient address
    if (!recipient.startsWith('synor:')) {
      setError('Invalid address format. Must start with "synor:"');
      return;
    }

    // Validate amount
    const amountNum = parseFloat(amount);
    if (isNaN(amountNum) || amountNum <= 0) {
      setError('Invalid amount');
      return;
    }

    // Check balance
    if (balance) {
      const confirmedBalance = parseFloat(balance.confirmed);
      if (amountNum > confirmedBalance) {
        setError('Insufficient balance');
        return;
      }
    }

    setIsLoading(true);

    try {
      // Create and sign transaction
      const signedTx = await createSendTransaction(address, recipient, amount, keypair);

      // Submit to node
      const client = getClient();
      const serialized = serializeTransaction(signedTx);
      const result = await client.submitTransaction(serialized);

      setSuccess({ txId: result.transactionId });
      refreshBalance();

      // Clear form
      setRecipient('');
      setAmount('');
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Transaction failed');
    } finally {
      setIsLoading(false);
    }
  };

  const handleSetMax = () => {
    if (balance) {
      // Leave some for fee
      const maxAmount = Math.max(0, parseFloat(balance.confirmed) - 0.001);
      setAmount(maxAmount.toString());
    }
  };

  if (success) {
    return (
      <div className="max-w-md mx-auto">
        <div className="card text-center">
          <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-green-900/50 flex items-center justify-center">
            <span className="text-3xl text-green-400">✓</span>
          </div>
          <h1 className="text-2xl font-bold mb-2">Transaction Sent</h1>
          <p className="text-slate-400 mb-4">
            Your transaction has been submitted to the network.
          </p>

          <div className="bg-slate-900 rounded-lg p-3 mb-6">
            <div className="text-xs text-slate-500 mb-1">Transaction ID</div>
            <div className="font-mono text-sm break-all">{success.txId}</div>
          </div>

          <div className="flex gap-4">
            <button
              onClick={() => setSuccess(null)}
              className="btn btn-secondary flex-1"
            >
              Send Another
            </button>
            <button
              onClick={() => navigate('/wallet')}
              className="btn btn-primary flex-1"
            >
              Back to Wallet
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-md mx-auto">
      <h1 className="text-2xl font-bold mb-6">Send SYNOR</h1>

      <form onSubmit={handleSend} className="card space-y-4">
        <div>
          <label className="block text-sm text-slate-400 mb-2">
            Recipient Address
          </label>
          <div className="flex gap-2">
            <input
              type="text"
              value={recipient}
              onChange={(e) => setRecipient(e.target.value)}
              className="input font-mono text-sm flex-1"
              placeholder="synor:qz..."
              autoFocus
            />
            <button
              type="button"
              onClick={() => setShowScanner(true)}
              className="btn btn-secondary px-3"
              title="Scan QR Code"
            >
              <svg
                className="w-5 h-5"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M12 4v1m6 11h2m-6 0h-2v4m0-11v3m0 0h.01M12 12h4.01M16 20h4M4 12h4m12 0h.01M5 8h2a1 1 0 001-1V5a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1zm12 0h2a1 1 0 001-1V5a1 1 0 00-1-1h-2a1 1 0 00-1 1v2a1 1 0 001 1zM5 20h2a1 1 0 001-1v-2a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1z"
                />
              </svg>
            </button>
          </div>
        </div>

        <div>
          <div className="flex items-center justify-between mb-2">
            <label className="text-sm text-slate-400">Amount</label>
            <button
              type="button"
              onClick={handleSetMax}
              className="text-xs text-synor-400 hover:text-synor-300"
            >
              Max: {balance?.confirmed || '0'} SYNOR
            </button>
          </div>
          <div className="relative">
            <input
              type="number"
              value={amount}
              onChange={(e) => setAmount(e.target.value)}
              className="input pr-20"
              placeholder="0.00"
              step="0.00000001"
              min="0"
            />
            <span className="absolute right-4 top-1/2 -translate-y-1/2 text-slate-400">
              SYNOR
            </span>
          </div>
        </div>

        {/* Fee estimate */}
        <div className="p-3 bg-slate-900 rounded-lg">
          <div className="flex justify-between text-sm">
            <span className="text-slate-400">Network Fee</span>
            <span>~0.0001 SYNOR</span>
          </div>
        </div>

        {error && (
          <div className="p-3 bg-red-900/50 border border-red-700 rounded-lg text-red-300 text-sm">
            {error}
          </div>
        )}

        <button
          type="submit"
          disabled={isLoading || !recipient || !amount}
          className="w-full btn btn-primary py-3"
        >
          {isLoading ? 'Sending...' : 'Send Transaction'}
        </button>
      </form>

      {/* QR Scanner Modal */}
      {showScanner && (
        <QRScanner
          onScan={handleQRScan}
          onClose={() => setShowScanner(false)}
          onError={(err) => {
            console.error('QR scan error:', err);
          }}
        />
      )}
    </div>
  );
}
