/**
 * @file TransferTracking.tsx
 * @notice Transfer tracking UI with status updates
 */

import { useState, useEffect } from 'react';
import toast from 'react-hot-toast';
import CopyButton from '../ui/CopyButton';
import Tooltip from '../ui/Tooltip';
import LoadingSkeleton from '../ui/LoadingSkeleton';

interface TransferStatus {
    transferId: string;
    status: string;
    depositor: string;
    asset: string;
    amount: string;
    destinationType: number;
    timestamp: number;
    isRefundable: boolean;
    executionData?: {
        txHash?: string;
        xrplTxHash?: string;
        fabricTxId?: string;
    };
}

interface TransferTrackingProps {
    transferId?: string;
}

export default function TransferTracking({ transferId: initialTransferId }: TransferTrackingProps) {
    const [transferId, setTransferId] = useState(initialTransferId || '');
    const [transfer, setTransfer] = useState<TransferStatus | null>(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [isPolling, setIsPolling] = useState(false);

    const fetchTransfer = async (id: string) => {
        setLoading(true);
        setError(null);

        try {
            const response = await fetch(`/api/bridge/status/${id}`);
            if (!response.ok) {
                throw new Error('Transfer not found');
            }

            const data = await response.json();
            setTransfer(data);
            if (data.status !== 'COMPLETED' && data.status !== 'FAILED') {
                setIsPolling(true);
            } else {
                setIsPolling(false);
            }
        } catch (err: any) {
            setError(err.message || 'Failed to fetch transfer');
            setTransfer(null);
            setIsPolling(false);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        if (transferId) {
            fetchTransfer(transferId);
            // Poll for updates every 5 seconds if not completed
            const interval = setInterval(() => {
                if (isPolling) {
                    fetchTransfer(transferId);
                }
            }, 5000);

            return () => clearInterval(interval);
        }
    }, [transferId, isPolling]);

    const getStatusColor = (status: string) => {
        const colors: Record<string, string> = {
            INITIATED: 'bg-gray-200 text-gray-800',
            DEPOSIT_CONFIRMED: 'bg-blue-200 text-blue-800',
            ROUTE_SELECTED: 'bg-yellow-200 text-yellow-800',
            EXECUTING: 'bg-purple-200 text-purple-800',
            DESTINATION_SENT: 'bg-green-200 text-green-800',
            FINALITY_CONFIRMED: 'bg-green-300 text-green-900',
            COMPLETED: 'bg-green-500 text-white',
            FAILED: 'bg-red-500 text-white',
            REFUND_PENDING: 'bg-orange-200 text-orange-800',
            REFUNDED: 'bg-gray-400 text-white'
        };
        return colors[status] || 'bg-gray-200 text-gray-800';
    };

    const getStatusIcon = (status: string) => {
        if (status === 'COMPLETED') {
            return (
                <svg className="w-5 h-5" 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>
            );
        }
        if (status === 'FAILED') {
            return (
                <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
            );
        }
        return (
            <svg className="w-5 h-5 animate-spin" 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>
        );
    };

    const getStatusLabel = (status: string) => {
        return status.replace(/_/g, ' ').toLowerCase()
            .replace(/\b\w/g, l => l.toUpperCase());
    };

    const handleTrack = () => {
        if (!transferId) {
            toast.error('Please enter a transfer ID');
            return;
        }
        fetchTransfer(transferId);
    };

    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">
                        Track Transfer
                    </h2>
                    <p className="text-gray-600">
                        Enter a transfer ID to track the status of your bridge transaction
                    </p>
                </div>

                <div className="mb-6">
                    <label className="block text-sm font-semibold mb-3 text-gray-700">
                        Transfer ID
                        <Tooltip content="Enter the transfer ID from your bridge transaction to track its status.">
                            <span className="ml-2 text-gray-400 cursor-help">ℹ️</span>
                        </Tooltip>
                    </label>
                    <div className="flex gap-3">
                        <input
                            type="text"
                            value={transferId}
                            onChange={(e) => setTransferId(e.target.value)}
                            onKeyDown={(e) => {
                                if (e.key === 'Enter') {
                                    handleTrack();
                                }
                            }}
                            placeholder="Enter transfer ID"
                            className="flex-1 p-4 border-2 border-gray-200 rounded-xl focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition-all font-mono text-sm bg-white"
                        />
                        <button
                            onClick={handleTrack}
                            disabled={loading || !transferId}
                            className="px-6 py-4 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 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>
                                    Loading...
                                </span>
                            ) : (
                                'Track'
                            )}
                        </button>
                    </div>
                </div>

                {error && (
                    <div className="mb-6 p-4 bg-red-50 border-2 border-red-200 text-red-700 rounded-xl flex items-start gap-3 animate-slideIn">
                        <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>
                )}

                {loading && !transfer && (
                    <div className="space-y-4">
                        <LoadingSkeleton lines={5} className="h-20" />
                    </div>
                )}

                {transfer && (
                    <div className="space-y-4 animate-scaleIn">
                        <div className="p-5 bg-gradient-to-br from-gray-50 to-blue-50 rounded-xl border border-gray-200/50">
                            <div className="flex justify-between items-center mb-4">
                                <span className="font-semibold text-gray-700">Status</span>
                                <span className={`px-4 py-2 rounded-lg font-semibold flex items-center gap-2 ${getStatusColor(transfer.status)}`}>
                                    {getStatusIcon(transfer.status)}
                                    {getStatusLabel(transfer.status)}
                                </span>
                            </div>
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-3 text-sm">
                                <div className="p-3 bg-white/60 rounded-lg">
                                    <span className="font-medium text-gray-600 block mb-1">Transfer ID:</span>
                                    <div className="flex items-center gap-2">
                                        <code className="font-mono text-xs text-gray-900 break-all">{transfer.transferId}</code>
                                        <CopyButton text={transfer.transferId} />
                                    </div>
                                </div>
                                <div className="p-3 bg-white/60 rounded-lg">
                                    <span className="font-medium text-gray-600 block mb-1">Amount:</span>
                                    <span className="font-bold text-gray-900">
                                        {transfer.amount} {transfer.asset === '0x0000000000000000000000000000000000000000' ? 'ETH' : 'tokens'}
                                    </span>
                                </div>
                                <div className="p-3 bg-white/60 rounded-lg">
                                    <span className="font-medium text-gray-600 block mb-1">Destination Type:</span>
                                    <span className="font-bold text-gray-900">
                                        {transfer.destinationType === 0 ? 'EVM' :
                                         transfer.destinationType === 1 ? 'XRPL' : 'Fabric'}
                                    </span>
                                </div>
                                <div className="p-3 bg-white/60 rounded-lg">
                                    <span className="font-medium text-gray-600 block mb-1">Initiated:</span>
                                    <span className="font-bold text-gray-900">
                                        {new Date(transfer.timestamp * 1000).toLocaleString()}
                                    </span>
                                </div>
                                <div className="p-3 bg-white/60 rounded-lg md:col-span-2">
                                    <span className="font-medium text-gray-600 block mb-1">Depositor:</span>
                                    <div className="flex items-center gap-2">
                                        <code className="font-mono text-xs text-gray-900 break-all">{transfer.depositor}</code>
                                        <CopyButton text={transfer.depositor} />
                                    </div>
                                </div>
                            </div>
                        </div>

                        {transfer.executionData && (
                            <div className="p-5 bg-gradient-to-br from-blue-50 to-purple-50 rounded-xl border border-blue-200/50">
                                <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 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                                    </svg>
                                    Execution Details
                                </h3>
                                <div className="space-y-2 text-sm">
                                    {transfer.executionData.txHash && (
                                        <div className="p-3 bg-white/60 rounded-lg">
                                            <span className="font-medium text-gray-600 block mb-1">EVM Transaction:</span>
                                            <div className="flex items-center gap-2">
                                                <code className="font-mono text-xs text-gray-900 break-all">{transfer.executionData.txHash}</code>
                                                <CopyButton text={transfer.executionData.txHash} />
                                            </div>
                                        </div>
                                    )}
                                    {transfer.executionData.xrplTxHash && (
                                        <div className="p-3 bg-white/60 rounded-lg">
                                            <span className="font-medium text-gray-600 block mb-1">XRPL Transaction:</span>
                                            <div className="flex items-center gap-2">
                                                <code className="font-mono text-xs text-gray-900 break-all">{transfer.executionData.xrplTxHash}</code>
                                                <CopyButton text={transfer.executionData.xrplTxHash} />
                                            </div>
                                        </div>
                                    )}
                                    {transfer.executionData.fabricTxId && (
                                        <div className="p-3 bg-white/60 rounded-lg">
                                            <span className="font-medium text-gray-600 block mb-1">Fabric Transaction:</span>
                                            <div className="flex items-center gap-2">
                                                <code className="font-mono text-xs text-gray-900 break-all">{transfer.executionData.fabricTxId}</code>
                                                <CopyButton text={transfer.executionData.fabricTxId} />
                                            </div>
                                        </div>
                                    )}
                                </div>
                            </div>
                        )}

                        {transfer.isRefundable && (
                            <div className="p-4 bg-orange-50 border-2 border-orange-200 rounded-xl flex items-start gap-3">
                                <svg className="w-5 h-5 text-orange-600 flex-shrink-0 mt-0.5" 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>
                                <div>
                                    <p className="font-semibold text-orange-800">Refund Available</p>
                                    <p className="text-sm text-orange-700 mt-1">
                                        This transfer is eligible for refund. Contact support to initiate refund.
                                    </p>
                                </div>
                            </div>
                        )}

                        {isPolling && (
                            <div className="p-3 bg-blue-50 border border-blue-200 rounded-xl text-sm text-blue-700 flex items-center gap-2">
                                <svg className="w-4 h-4 animate-spin" 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>
                                <span>Auto-refreshing every 5 seconds...</span>
                            </div>
                        )}
                    </div>
                )}

                {!transfer && !loading && !error && transferId && (
                    <div className="text-center py-12 text-gray-500 bg-gray-50 rounded-xl border-2 border-dashed border-gray-300">
                        <svg className="mx-auto h-12 w-12 text-gray-400 mb-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                        </svg>
                        <p className="text-lg font-medium">No transfer found</p>
                        <p className="text-sm mt-2">Please check the transfer ID and try again</p>
                    </div>
                )}

                {!transfer && !loading && !error && !transferId && (
                    <div className="text-center py-12 text-gray-500 bg-gray-50 rounded-xl border-2 border-dashed border-gray-300">
                        <svg className="mx-auto h-12 w-12 text-gray-400 mb-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                        </svg>
                        <p className="text-lg font-medium">Enter a transfer ID to track</p>
                        <p className="text-sm mt-2">Paste your transfer ID above to view its status</p>
                    </div>
                )}
            </div>
        </div>
    );
}
