/**
 * @file XRPLBridgeForm.tsx
 * @notice Custom XRPL bridge UI for bridging to XRPL
 */

import { useState } from 'react';
import { useAccount } from 'wagmi';
import toast from 'react-hot-toast';
import CopyButton from '../ui/CopyButton';
import Tooltip from '../ui/Tooltip';
import ConfirmationModal from '../ui/ConfirmationModal';

interface XRPLBridgeFormProps {
    onBridge: (data: XRPLBridgeData) => Promise<void>;
}

export interface XRPLBridgeData {
    amount: string;
    destinationAddress: string;
    destinationTag?: number;
    token: string; // address(0) for native
}

export default function XRPLBridgeForm({ onBridge }: XRPLBridgeFormProps) {
    const { address } = useAccount();
    const [amount, setAmount] = useState('');
    const [destinationAddress, setDestinationAddress] = useState('');
    const [destinationTag, setDestinationTag] = useState('');
    const [token, setToken] = useState('native'); // 'native' or token address
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [quote, setQuote] = useState<any>(null);
    const [showConfirmModal, setShowConfirmModal] = useState(false);
    const [amountError, setAmountError] = useState<string>('');
    const [addressError, setAddressError] = useState<string>('');

    const validateAmount = (value: string) => {
        if (!value) {
            setAmountError('');
            return;
        }
        const numValue = parseFloat(value);
        if (isNaN(numValue) || numValue <= 0) {
            setAmountError('Amount must be greater than 0');
        } else {
            setAmountError('');
        }
    };

    const validateXRPLAddress = (value: string) => {
        if (!value) {
            setAddressError('');
            return;
        }
        if (!value.startsWith('r') || value.length < 25 || value.length > 35) {
            setAddressError('Invalid XRPL address (must start with "r" and be 25-35 characters)');
        } else {
            setAddressError('');
        }
    };

    const handleGetQuote = async () => {
        if (!amount || !destinationAddress) {
            setError('Please enter amount and destination address');
            toast.error('Please fill in all required fields');
            return;
        }

        if (amountError || addressError) {
            toast.error('Please fix the errors before getting a quote');
            return;
        }

        try {
            setError(null);
            const toastId = toast.loading('Getting quote...');
            // Call quote API
            const response = await fetch('/api/bridge/xrpl/quote', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    token: token === 'native' ? '0x0000000000000000000000000000000000000000' : token,
                    amount,
                    destinationAddress,
                    destinationTag: destinationTag ? Number(destinationTag) : undefined
                })
            });

            if (!response.ok) {
                throw new Error('Failed to get quote');
            }

            const quoteData = await response.json();
            setQuote(quoteData);
            toast.success('Quote received successfully!', { id: toastId });
        } catch (err: any) {
            const errorMsg = err.message || 'Failed to get quote';
            setError(errorMsg);
            toast.error(errorMsg);
        }
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!address) {
            setError('Please connect your wallet');
            toast.error('Please connect your wallet');
            return;
        }

        if (!amount || !destinationAddress) {
            setError('Please fill in all required fields');
            toast.error('Please fill in all required fields');
            return;
        }

        if (amountError || addressError) {
            toast.error('Please fix the errors before bridging');
            return;
        }

        setShowConfirmModal(true);
    };

    const handleConfirmBridge = async () => {
        setShowConfirmModal(false);
        setLoading(true);
        setError(null);
        const toastId = toast.loading('Bridging to XRPL...');

        try {
            await onBridge({
                amount,
                destinationAddress,
                destinationTag: destinationTag ? Number(destinationTag) : undefined,
                token: token === 'native' ? '0x0000000000000000000000000000000000000000' : token
            });
            toast.success('Bridge initiated successfully!', { id: toastId });
            // Reset form
            setAmount('');
            setDestinationAddress('');
            setDestinationTag('');
            setQuote(null);
        } catch (err: any) {
            const errorMsg = err.message || 'Bridge failed';
            setError(errorMsg);
            toast.error(errorMsg, { id: toastId });
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="w-full max-w-3xl mx-auto">
            <div className="bg-white/90 backdrop-blur-sm rounded-2xl shadow-2xl border border-gray-200/50 p-6 md:p-8 animate-fadeIn">
                <div className="mb-6">
                    <h2 className="text-3xl font-bold mb-2 bg-gradient-to-r from-blue-600 via-purple-600 to-pink-600 bg-clip-text text-transparent">
                        Bridge to XRPL
                    </h2>
                    <p className="text-gray-600">
                        Bridge tokens from Chain 138 to XRPL and receive native XRP
                    </p>
                </div>

                <form onSubmit={handleSubmit} className="space-y-6">
                    <div>
                        <label className="block text-sm font-semibold mb-3 text-gray-700">
                            Token
                            <Tooltip content="Select the token you want to bridge. Native ETH will be converted to XRP.">
                                <span className="ml-2 text-gray-400 cursor-help">ℹ️</span>
                            </Tooltip>
                        </label>
                        <select
                            value={token}
                            onChange={(e) => setToken(e.target.value)}
                            className="w-full p-4 border-2 border-gray-200 rounded-xl focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition-all bg-white font-medium"
                        >
                            <option value="native">Native ETH</option>
                            <option value="0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2">WETH</option>
                            {/* Add more tokens as needed */}
                        </select>
                    </div>

                    <div>
                        <label className="block text-sm font-semibold mb-3 text-gray-700">
                            Amount
                            <Tooltip content="Enter the amount you want to bridge to XRPL.">
                                <span className="ml-2 text-gray-400 cursor-help">ℹ️</span>
                            </Tooltip>
                        </label>
                        <input
                            type="text"
                            value={amount}
                            onChange={(e) => {
                                setAmount(e.target.value);
                                validateAmount(e.target.value);
                            }}
                            onBlur={(e) => validateAmount(e.target.value)}
                            placeholder="0.0"
                            className={`w-full p-4 border-2 rounded-xl focus:ring-2 focus:ring-blue-200 transition-all font-medium bg-white ${
                                amountError ? 'border-red-300 focus:border-red-500' : 'border-gray-200 focus:border-blue-500'
                            }`}
                            required
                            aria-invalid={!!amountError}
                            aria-describedby={amountError ? 'amount-error' : undefined}
                        />
                        {amountError && (
                            <p id="amount-error" className="mt-2 text-sm text-red-600 flex items-center gap-1">
                                <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                                </svg>
                                {amountError}
                            </p>
                        )}
                    </div>

                    <div>
                        <label className="block text-sm font-semibold mb-3 text-gray-700">
                            XRPL Destination Address
                            <Tooltip content="Enter a valid XRPL address (starts with 'r' and is 25-35 characters long).">
                                <span className="ml-2 text-gray-400 cursor-help">ℹ️</span>
                            </Tooltip>
                        </label>
                        <div className="relative">
                            <input
                                type="text"
                                value={destinationAddress}
                                onChange={(e) => {
                                    setDestinationAddress(e.target.value);
                                    validateXRPLAddress(e.target.value);
                                }}
                                onBlur={(e) => validateXRPLAddress(e.target.value)}
                                placeholder="rXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
                                className={`w-full p-4 border-2 rounded-xl focus:ring-2 focus:ring-blue-200 transition-all font-mono text-sm bg-white ${
                                    addressError ? 'border-red-300 focus:border-red-500' : 'border-gray-200 focus:border-blue-500'
                                }`}
                                required
                                aria-invalid={!!addressError}
                                aria-describedby={addressError ? 'address-error' : undefined}
                            />
                            {destinationAddress && !addressError && (
                                <div className="absolute right-3 top-1/2 -translate-y-1/2">
                                    <CopyButton text={destinationAddress} />
                                </div>
                            )}
                        </div>
                        {addressError && (
                            <p id="address-error" className="mt-2 text-sm text-red-600 flex items-center gap-1">
                                <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                                </svg>
                                {addressError}
                            </p>
                        )}
                        <p className="text-xs text-gray-500 mt-1">
                            Enter a valid XRPL address (starts with 'r')
                        </p>
                    </div>

                    <div>
                        <label className="block text-sm font-semibold mb-3 text-gray-700">
                            Destination Tag (Optional)
                            <Tooltip content="Some XRPL exchanges require a destination tag. Leave empty if not needed.">
                                <span className="ml-2 text-gray-400 cursor-help">ℹ️</span>
                            </Tooltip>
                        </label>
                        <input
                            type="number"
                            value={destinationTag}
                            onChange={(e) => setDestinationTag(e.target.value)}
                            placeholder="Optional"
                            className="w-full p-4 border-2 border-gray-200 rounded-xl focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition-all bg-white font-medium"
                        />
                    </div>

                    <div className="flex flex-col sm:flex-row gap-3">
                        <button
                            type="button"
                            onClick={handleGetQuote}
                            disabled={!amount || !destinationAddress || !!amountError || !!addressError}
                            className="flex-1 px-6 py-3 bg-gradient-to-r from-gray-500 to-gray-600 text-white rounded-xl font-semibold hover:from-gray-600 hover:to-gray-700 disabled:from-gray-300 disabled:to-gray-400 disabled:cursor-not-allowed disabled:opacity-50 transition-all duration-200 shadow-lg hover:shadow-xl transform hover:scale-105 disabled:transform-none"
                        >
                            Get Quote
                        </button>
                        <button
                            type="submit"
                            disabled={loading || !address || !!amountError || !!addressError}
                            className="flex-1 px-6 py-3 bg-gradient-to-r from-blue-600 to-purple-600 text-white rounded-xl font-semibold hover:from-blue-700 hover:to-purple-700 disabled:from-gray-300 disabled:to-gray-400 disabled:cursor-not-allowed disabled:opacity-50 transition-all duration-200 shadow-lg hover:shadow-xl transform hover:scale-105 disabled:transform-none"
                        >
                            {loading ? (
                                <span className="flex items-center justify-center gap-2">
                                    <svg className="animate-spin h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                    </svg>
                                    Bridging...
                                </span>
                            ) : (
                                'Bridge to XRPL'
                            )}
                        </button>
                    </div>

                    {error && (
                        <div className="p-4 bg-red-50 border-2 border-red-200 text-red-700 rounded-xl flex items-start gap-3">
                            <svg className="w-5 h-5 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                            </svg>
                            <div>
                                <p className="font-semibold">Error</p>
                                <p className="text-sm">{error}</p>
                            </div>
                        </div>
                    )}

                    {quote && (
                        <div className="p-5 bg-gradient-to-br from-blue-50 to-purple-50 rounded-xl border border-blue-200/50 animate-scaleIn">
                            <h3 className="font-semibold mb-3 text-gray-900 flex items-center gap-2">
                                <svg className="w-5 h-5 text-blue-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                                </svg>
                                Quote Details
                            </h3>
                            <div className="space-y-2 text-sm">
                                <div className="flex justify-between items-center p-2 bg-white/60 rounded-lg">
                                    <span className="font-medium text-gray-600">Fee:</span>
                                    <span className="font-bold text-gray-900">{quote.fee} {token === 'native' ? 'ETH' : 'tokens'}</span>
                                </div>
                                <div className="flex justify-between items-center p-2 bg-white/60 rounded-lg">
                                    <span className="font-medium text-gray-600">You'll receive:</span>
                                    <span className="font-bold text-green-600">{quote.minReceived} XRP</span>
                                </div>
                                <div className="flex justify-between items-center p-2 bg-white/60 rounded-lg">
                                    <span className="font-medium text-gray-600">Estimated time:</span>
                                    <span className="font-bold text-gray-900">{quote.estimatedTime} seconds</span>
                                </div>
                            </div>
                        </div>
                    )}
                </form>

                {!address && (
                    <div className="mt-6 p-4 bg-gradient-to-r from-yellow-50 to-orange-50 border-2 border-yellow-300 rounded-xl text-sm text-yellow-800 flex items-center gap-3">
                        <svg className="h-5 w-5 text-yellow-600 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                        </svg>
                        <span className="font-semibold">Please connect your wallet to continue</span>
                    </div>
                )}

                <ConfirmationModal
                    isOpen={showConfirmModal}
                    onClose={() => setShowConfirmModal(false)}
                    onConfirm={handleConfirmBridge}
                    title="Bridge to XRPL"
                    message={`You are about to bridge ${amount} ${token === 'native' ? 'ETH' : 'tokens'} to ${destinationAddress.slice(0, 10)}...${destinationAddress.slice(-8)} on XRPL. This action cannot be undone.`}
                    confirmText="Confirm Bridge"
                    confirmColor="purple"
                    isLoading={loading}
                />
            </div>
        </div>
    );
}
