import { useState } from 'react';
import ThirdwebBridgeWidget from '../components/bridge/ThirdwebBridgeWidget';
import BridgeButtons from '../components/bridge/BridgeButtons';
import XRPLBridgeForm, { XRPLBridgeData } from '../components/bridge/XRPLBridgeForm';
import TransferTracking from '../components/bridge/TransferTracking';
import SwapBridgeSwapQuoteForm from '../components/bridge/SwapBridgeSwapQuoteForm';
import TrustlessBridgeForm from '../components/bridge/TrustlessBridgeForm';
import ChainIcon from '../components/ui/ChainIcon';
import { CCIP_DESTINATIONS, CHAIN_SELECTORS } from '../config/bridge';
import { chain138 } from '../config/networks';

const THIRDWEB_CLIENT_ID = import.meta.env.VITE_THIRDWEB_CLIENT_ID || '542981292d51ec610388ba8985f027d7';

export default function BridgePage() {
    const [activeTab, setActiveTab] = useState<'custom' | 'trustless' | 'evm' | 'xrpl' | 'track'>('custom');
    const [transferId, setTransferId] = useState<string | undefined>();
    const [ccipDestinationSelector, setCcipDestinationSelector] = useState<string>(CHAIN_SELECTORS.ETHEREUM_MAINNET);

    const handleXRPLBridge = async (data: XRPLBridgeData) => {
        try {
            const response = await fetch('/api/bridge/xrpl/initiate', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            });

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

            const result = await response.json();
            setTransferId(result.transferId);
            setActiveTab('track');
        } catch (error: unknown) {
            throw new Error(error instanceof Error ? error.message : 'Bridge initiation failed');
        }
    };

    return (
        <div className="min-h-screen relative">
            <div className="container mx-auto px-4 sm:px-6 py-8 sm:py-12 max-w-7xl relative z-10 w-full">
                <div className="text-center mb-8">
                    <h1 className="text-[32px] font-bold text-white mb-2">
                        Interoperability Bridge
                    </h1>
                    <p className="text-[#A0A0A0] text-base">
                        Bridge assets between Chain 138 and Ethereum via CCIP
                    </p>
                </div>

                {/* Tabs — text only, no icons */}
                <div className="mb-6">
                    <nav className="flex flex-wrap gap-1 bg-[#252830] rounded-xl p-1.5 border border-white/10" role="tablist">
                        <button
                            onClick={() => setActiveTab('custom')}
                            role="tab"
                            aria-selected={activeTab === 'custom'}
                            aria-controls="custom-tabpanel"
                            id="custom-tab"
                            className={`px-4 py-3 text-sm font-medium rounded-lg transition-all focus:outline-none focus:ring-2 focus:ring-teal-500/50 ${
                                activeTab === 'custom'
                                    ? 'bg-teal-600 text-white'
                                    : 'text-[#A0A0A0] hover:text-white hover:bg-white/5'
                            }`}
                        >
                            Custom
                        </button>
                        <button
                            onClick={() => setActiveTab('trustless')}
                            role="tab"
                            aria-selected={activeTab === 'trustless'}
                            aria-controls="trustless-tabpanel"
                            id="trustless-tab"
                            className={`px-4 py-3 text-sm font-medium rounded-lg transition-all focus:outline-none focus:ring-2 focus:ring-teal-500/50 ${
                                activeTab === 'trustless'
                                    ? 'bg-teal-600 text-white'
                                    : 'text-[#A0A0A0] hover:text-white hover:bg-white/5'
                            }`}
                        >
                            Trustless
                        </button>
                        <button
                            onClick={() => setActiveTab('evm')}
                            role="tab"
                            aria-selected={activeTab === 'evm'}
                            aria-controls="evm-tabpanel"
                            id="evm-tab"
                            className={`px-4 py-3 text-sm font-medium rounded-lg transition-all focus:outline-none focus:ring-2 focus:ring-teal-500/50 ${
                                activeTab === 'evm'
                                    ? 'bg-teal-600 text-white'
                                    : 'text-[#A0A0A0] hover:text-white hover:bg-white/5'
                            }`}
                        >
                            ThirdWeb
                        </button>
                        <button
                            onClick={() => setActiveTab('xrpl')}
                            role="tab"
                            aria-selected={activeTab === 'xrpl'}
                            aria-controls="xrpl-tabpanel"
                            id="xrpl-tab"
                            className={`px-4 py-3 text-sm font-medium rounded-lg transition-all focus:outline-none focus:ring-2 focus:ring-teal-500/50 ${
                                activeTab === 'xrpl'
                                    ? 'bg-teal-600 text-white'
                                    : 'text-[#A0A0A0] hover:text-white hover:bg-white/5'
                            }`}
                        >
                            XRPL
                        </button>
                        <button
                            onClick={() => setActiveTab('track')}
                            role="tab"
                            aria-selected={activeTab === 'track'}
                            aria-controls="track-tabpanel"
                            id="track-tab"
                            className={`px-4 py-3 text-sm font-medium rounded-lg transition-all focus:outline-none focus:ring-2 focus:ring-teal-500/50 ${
                                activeTab === 'track'
                                    ? 'bg-teal-600 text-white'
                                    : 'text-[#A0A0A0] hover:text-white hover:bg-white/5'
                            }`}
                        >
                            Track
                        </button>
                    </nav>
                </div>

                {/* Content */}
                <div className="mt-6 animate-fadeIn">
                    {activeTab === 'trustless' && (
                        <div role="tabpanel" id="trustless-tabpanel" aria-labelledby="trustless-tab">
                            <TrustlessBridgeForm />
                        </div>
                    )}
                    {activeTab === 'custom' && (
                        <div role="tabpanel" id="custom-tabpanel" aria-labelledby="custom-tab" className="w-full max-w-2xl mx-auto">
                            <div className="bg-[#252830] rounded-2xl border border-white/10 shadow-xl p-4 sm:p-6 md:p-8 w-full">
                                <div className="mb-4 flex flex-wrap items-center gap-6">
                                    <div className="flex items-center gap-2">
                                        <span className="text-[#A0A0A0] font-medium">From</span>
                                        <ChainIcon chainId={chain138.id} name={chain138.name} size={28} />
                                        <span className="text-white font-medium">{chain138.name}</span>
                                    </div>
                                    <div className="flex items-center gap-2">
                                        <span className="text-[#A0A0A0] font-medium">To</span>
                                        {CCIP_DESTINATIONS.map((d) => d.selector === ccipDestinationSelector && (
                                            <ChainIcon key={d.chainId} chainId={d.chainId} name={d.name} size={28} />
                                        ))}
                                        <select
                                            value={ccipDestinationSelector}
                                            onChange={(e) => setCcipDestinationSelector(e.target.value)}
                                            className="px-3 py-2 rounded-lg bg-[#1a1d24] text-white border border-white/20 min-w-[200px] focus:ring-2 focus:ring-teal-500/50 focus:border-teal-500"
                                        >
                                            {CCIP_DESTINATIONS.map((d) => (
                                                <option key={d.chainId} value={d.selector}>{d.name}</option>
                                            ))}
                                        </select>
                                    </div>
                                </div>
                                <SwapBridgeSwapQuoteForm />
                                <BridgeButtons
                                    destinationChainSelector={ccipDestinationSelector}
                                    recipientAddress={undefined}
                                />
                            </div>
                        </div>
                    )}
                    {activeTab === 'evm' && (
                        <div role="tabpanel" id="evm-tabpanel" aria-labelledby="evm-tab">
                            <ThirdwebBridgeWidget clientId={THIRDWEB_CLIENT_ID} />
                        </div>
                    )}
                    {activeTab === 'xrpl' && (
                        <div role="tabpanel" id="xrpl-tabpanel" aria-labelledby="xrpl-tab">
                            <XRPLBridgeForm onBridge={handleXRPLBridge} />
                        </div>
                    )}
                    {activeTab === 'track' && (
                        <div role="tabpanel" id="track-tabpanel" aria-labelledby="track-tab">
                            <TransferTracking transferId={transferId} />
                        </div>
                    )}
                </div>

            </div>
        </div>
    );
}
