import { useState } from 'react';
import { invoke } from '@tauri-apps/api/core';
import { Send as SendIcon, AlertTriangle, Check } from 'lucide-react';
import { useWalletStore } from '../store/wallet';

/**
 * Convert a decimal string to sompi (smallest unit) without floating point errors
 * 1 SYN = 100_000_000 sompi (8 decimal places)
 *
 * Examples:
 *   "1.5" -> 150000000
 *   "0.00000001" -> 1
 *   "123.45678901" -> 12345678901 (truncates extra decimals)
 */
function parseSynToSompi(amountStr: string): bigint | null {
  const DECIMALS = 8;
  const MULTIPLIER = BigInt(10 ** DECIMALS);

  // Clean the input
  const cleaned = amountStr.trim();
  if (!cleaned || cleaned === '.') {
    return null;
  }

  // Validate format (positive decimal number)
  if (!/^\d*\.?\d*$/.test(cleaned)) {
    return null;
  }

  // Split into integer and decimal parts
  const parts = cleaned.split('.');
  const integerPart = parts[0] || '0';
  let decimalPart = parts[1] || '';

  // Truncate or pad decimal part to exactly 8 digits
  if (decimalPart.length > DECIMALS) {
    decimalPart = decimalPart.slice(0, DECIMALS);
  } else {
    decimalPart = decimalPart.padEnd(DECIMALS, '0');
  }

  // Combine and convert to BigInt
  const combined = integerPart + decimalPart;
  const result = BigInt(combined);

  return result > 0n ? result : null;
}

export default function Send() {
  const { balance } = useWalletStore();

  const [to, setTo] = useState('');
  const [amount, setAmount] = useState('');
  const [useDilithium, setUseDilithium] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

  const handleSend = async () => {
    setLoading(true);
    setError('');
    setSuccess('');

    try {
      // Convert amount to sompi using precise string parsing (no floating point)
      const amountSompiBigInt = parseSynToSompi(amount);

      if (amountSompiBigInt === null) {
        throw new Error('Invalid amount');
      }

      // Convert to number for the API (safe for values under 2^53)
      const amountSompi = Number(amountSompiBigInt);
      if (!Number.isSafeInteger(amountSompi)) {
        throw new Error('Amount too large');
      }

      // Create transaction
      const unsigned = await invoke<{ tx_hex: string; fee: number }>(
        'create_transaction',
        {
          request: {
            to,
            amount: amountSompi,
            use_dilithium: useDilithium,
          },
        }
      );

      // Sign transaction
      const signed = await invoke<{ tx_hex: string; txid: string }>(
        'sign_transaction',
        { tx_hex: unsigned.tx_hex }
      );

      // Broadcast transaction
      const result = await invoke<{ txid: string; accepted: boolean }>(
        'broadcast_transaction',
        { tx_hex: signed.tx_hex }
      );

      if (result.accepted) {
        setSuccess(`Transaction sent! TXID: ${result.txid}`);
        setTo('');
        setAmount('');
      } else {
        throw new Error('Transaction rejected by network');
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to send transaction');
    } finally {
      setLoading(false);
    }
  };

  const maxAmount = balance ? balance.balance / 100_000_000 : 0;

  return (
    <div className="max-w-lg">
      <h1 className="text-2xl font-bold text-white mb-6">Send SYN</h1>

      <div className="card space-y-6">
        {/* Recipient */}
        <div>
          <label className="block text-sm text-gray-400 mb-2">
            Recipient Address
          </label>
          <input
            type="text"
            value={to}
            onChange={(e) => setTo(e.target.value)}
            className="input font-mono text-sm"
            placeholder="synor1..."
          />
        </div>

        {/* Amount */}
        <div>
          <label className="block text-sm text-gray-400 mb-2">Amount</label>
          <div className="relative">
            <input
              type="number"
              value={amount}
              onChange={(e) => setAmount(e.target.value)}
              className="input pr-20"
              placeholder="0.00"
              step="0.00000001"
            />
            <div className="absolute right-3 top-1/2 -translate-y-1/2 flex items-center gap-2">
              <button
                onClick={() => setAmount(maxAmount.toString())}
                className="text-xs text-synor-400 hover:text-synor-300"
              >
                MAX
              </button>
              <span className="text-gray-500">SYN</span>
            </div>
          </div>
          <p className="text-sm text-gray-500 mt-1">
            Available: {maxAmount.toFixed(8)} SYN
          </p>
        </div>

        {/* Post-quantum signature option */}
        <div className="flex items-center gap-3 p-4 bg-gray-950 rounded-lg">
          <input
            type="checkbox"
            id="dilithium"
            checked={useDilithium}
            onChange={(e) => setUseDilithium(e.target.checked)}
            className="w-4 h-4 rounded border-gray-600 text-synor-500 focus:ring-synor-500"
          />
          <label htmlFor="dilithium" className="flex-1">
            <p className="text-white text-sm font-medium">
              Use Dilithium3 Signature
            </p>
            <p className="text-gray-500 text-xs">
              Post-quantum secure, but higher fees (~5x larger signature)
            </p>
          </label>
        </div>

        {/* Error/Success messages */}
        {error && (
          <div className="flex items-center gap-2 text-red-400 text-sm">
            <AlertTriangle size={16} />
            {error}
          </div>
        )}

        {success && (
          <div className="flex items-center gap-2 text-green-400 text-sm">
            <Check size={16} />
            {success}
          </div>
        )}

        {/* Send button */}
        <button
          onClick={handleSend}
          disabled={loading || !to || !amount}
          className="btn btn-primary w-full"
        >
          {loading ? (
            'Sending...'
          ) : (
            <>
              <SendIcon size={18} />
              Send Transaction
            </>
          )}
        </button>
      </div>
    </div>
  );
}
