import React from 'react'
import {useQuery, useQueryClient} from '@tanstack/react-query'
import useApiUrlStore from '../../app/store/apiStore'
import {fetchPlatformData} from '../../services/platformService'

function PlatformSummary({index}: { index: number }) {
    const {apiUrl} = useApiUrlStore()
    const queryClient = useQueryClient()

    const {
        data,
        isLoading,
        error,
        isFetching
    } = useQuery({
        queryKey: ['platformData', apiUrl],
        queryFn: () => fetchPlatformData(apiUrl),
        refetchInterval: 30000, // Refetch every 30 seconds
        staleTime: 25000, // Consider data stale after 25 seconds
        placeholderData: (previousData) => previousData, // Keep previous data while fetching
        enabled: !!apiUrl
    })

    const platformData = data?.platform
    const topStrategies = data?.topStrategies
    const topStrategiesByRoi = data?.topStrategiesByRoi
    const topAgentsByPnL = data?.topAgentsByPnL

    const formatCurrency = (value: number) => {
        if (value >= 1000000) {
            return `$${(value / 1000000).toFixed(2)}M`
        } else if (value >= 1000) {
            return `$${(value / 1000).toFixed(2)}K`
        }
        return `$${value.toFixed(2)}`
    }

    const formatNumber = (value: number) => {
        if (value >= 1000) {
            return value.toLocaleString()
        }
        return value.toString()
    }

    const formatChangeIndicator = (change: number) => {
        if (change > 0) {
            return (
                <span className="text-green-500">
          +{change} Today
        </span>
            )
        } else if (change < 0) {
            return (
                <span className="text-red-500">
          {change} Today
        </span>
            )
        }
        return (
            <span className="text-gray-500">
        No change
      </span>
        )
    }

    const formatPercentageChange = (current: number, change: number) => {
        if (current === 0) return '0%'
        const percentage = (change / (current - change)) * 100
        return `${percentage >= 0 ? '+' : ''}${percentage.toFixed(1)}%`
    }

    const handleForceRefresh = async () => {
        await queryClient.invalidateQueries({
            queryKey: ['platformData', apiUrl]
        })
    }

    // Show loading spinner only on initial load
    if (isLoading && !data) {
        return (
            <div className="flex justify-center items-center min-h-96">
                <div className="loading loading-spinner loading-lg"></div>
            </div>
        )
    }

    if (error && !data) {
        return (
            <div className="alert alert-error">
                <span>Failed to fetch platform data</span>
                <details className="text-sm mt-2">
                    {error instanceof Error ? error.message : 'Unknown error occurred'}
                </details>
            </div>
        )
    }

    return (
        <div className="p-6 bg-base-100 min-h-screen">
            {/* Subtle refetching indicator */}
            {isFetching && data && (
                <div className="fixed top-4 right-4 z-50">
                    <div className="bg-blue-500 text-white px-3 py-1 rounded-full text-sm flex items-center gap-2">
                        <div className="loading loading-spinner loading-xs"></div>
                        Updating...
                    </div>
                </div>
            )}

            {/* Header */}
            <div className="mb-8">
                <h1 className="text-4xl font-bold text-white mb-2">
                    {formatNumber(platformData?.totalActiveStrategies || 0)} Strategies Deployed
                </h1>
                <div className="text-lg">
                    {platformData && formatChangeIndicator(platformData.strategiesChange24h || 0)}
                </div>
            </div>

            {/* Main Stats Grid */}
            <div className="grid grid-cols-1 lg:grid-cols-4 gap-6 mb-8">
                {/* Total Volume Traded */}
                <div className="bg-base-200 rounded-lg p-6">
                    <h3 className="text-lg font-semibold text-gray-400 mb-2">Total Volume Traded</h3>
                    <div className="text-3xl font-bold text-white mb-1">
                        {formatCurrency(platformData?.totalPlatformVolume || 0)}
                    </div>
                    <div
                        className={`text-sm ${(platformData?.volumeChange24h || 0) >= 0 ? 'text-green-500' : 'text-red-500'}`}>
                        {(platformData?.volumeChange24h || 0) >= 0 ? '+' : ''}{formatCurrency(platformData?.volumeChange24h || 0)} Today
                        <span className="ml-2 text-gray-400">
              ({formatPercentageChange(platformData?.totalPlatformVolume || 0, platformData?.volumeChange24h || 0)})
            </span>
                    </div>
                    {/* Simple chart placeholder - you can replace with actual chart */}
                    <div className="mt-4 h-16 flex items-end">
                        <div className="w-full h-8 bg-green-500 rounded opacity-20"></div>
                    </div>
                </div>

                {/* Top 3 Most Profitable */}
                <div className="bg-base-200 rounded-lg p-6">
                    <div className="flex items-center gap-2 mb-4">
                        <span className="text-2xl">🤑</span>
                        <h3 className="text-lg font-semibold text-gray-400">Top 3 Most Profitable</h3>
                    </div>
                    <div className="space-y-3">
                        {topStrategies?.topStrategies?.slice(0, 3).map((strategy, index) => (
                            <div key={index} className="flex items-center justify-between">
                                <div className="flex items-center gap-3">
                                    <div className="w-8 h-8 bg-blue-500 rounded-full flex items-center justify-center">
                    <span className="text-xs font-bold text-white">
                      {strategy.strategyName?.charAt(0) || 'S'}
                    </span>
                                    </div>
                                    <div>
                                        <div className="text-sm text-white font-medium">
                                            {strategy.strategyName || '[Strategy Name]'}
                                        </div>
                                        <div className="text-xs text-gray-400">📧</div>
                                    </div>
                                </div>
                                <div
                                    className={`text-sm font-bold ${strategy.pnL && strategy.pnL >= 0 ? 'text-green-500' : 'text-red-500'}`}>
                                    {strategy.pnL && strategy.pnL >= 0 ? '+' : ''}{formatCurrency(strategy.pnL || 0)}
                                </div>
                            </div>
                        )) || (
                            <div className="text-gray-500 text-sm">No profitable strategies found</div>
                        )}
                    </div>
                </div>

                {/* Top 3 Rising (by ROI) */}
                <div className="bg-base-200 rounded-lg p-6">
                    <div className="flex items-center gap-2 mb-4">
                        <span className="text-2xl">📈</span>
                        <h3 className="text-lg font-semibold text-gray-400">Top 3 by ROI</h3>
                    </div>
                    <div className="space-y-3">
                        {topStrategiesByRoi?.topStrategiesByRoi?.slice(0, 3).map((strategy, index) => (
                            <div key={index} className="flex items-center justify-between">
                                <div className="flex items-center gap-3">
                                    <div className="w-8 h-8 bg-green-500 rounded-full flex items-center justify-center">
                    <span className="text-xs font-bold text-white">
                      {strategy.strategyName?.charAt(0) || 'S'}
                    </span>
                                    </div>
                                    <div>
                                        <div className="text-sm text-white font-medium">
                                            {strategy.strategyName || '[Strategy Name]'}
                                        </div>
                                        <div className="text-xs text-gray-400">
                                            Vol: {formatCurrency(strategy.volume || 0)}
                                        </div>
                                    </div>
                                </div>
                                <div className="text-right">
                                    <div
                                        className={`text-sm font-bold ${(strategy.roi || 0) >= 0 ? 'text-green-500' : 'text-red-500'}`}>
                                        {(strategy.roi || 0) >= 0 ? '+' : ''}{strategy.roi?.toFixed(2) || 0}%
                                    </div>
                                    <div
                                        className={`text-xs ${(strategy.pnL || 0) >= 0 ? 'text-green-400' : 'text-red-400'}`}>
                                        {(strategy.pnL || 0) >= 0 ? '+' : ''}{formatCurrency(strategy.pnL || 0)}
                                    </div>
                                </div>
                            </div>
                        )) || (
                            <div className="text-gray-500 text-sm">No ROI data available</div>
                        )}
                    </div>
                </div>

                {/* Top 3 Agents by PnL */}
                <div className="bg-base-200 rounded-lg p-6">
                    <div className="flex items-center gap-2 mb-4">
                        <span className="text-2xl">👥</span>
                        <h3 className="text-lg font-semibold text-gray-400">Top 3 Agents by PnL</h3>
                    </div>
                    <div className="space-y-3">
                        {topAgentsByPnL?.topAgentsByPnL?.slice(0, 3).map((agent, index) => (
                            <div key={index} className="flex items-center justify-between">
                                <div className="flex items-center gap-3">
                                    <div className="w-8 h-8 bg-purple-500 rounded-full flex items-center justify-center">
                    <span className="text-xs font-bold text-white">
                      {agent.agentName?.charAt(0) || 'A'}
                    </span>
                                    </div>
                                    <div>
                                        <div className="text-sm text-white font-medium">
                                            {agent.agentName || '[Agent Name]'}
                                        </div>
                                        <div className="text-xs text-gray-400">
                                            {agent.activeStrategiesCount || 0} strategies
                                        </div>
                                    </div>
                                </div>
                                <div className="text-right">
                                    <div
                                        className={`text-sm font-bold ${(agent.pnL || 0) >= 0 ? 'text-green-500' : 'text-red-500'}`}>
                                        {(agent.pnL || 0) >= 0 ? '+' : ''}{formatCurrency(agent.pnL || 0)}
                                    </div>
                                    <div className="text-xs text-gray-400">
                                        {(agent.totalROI || 0).toFixed(2)}% ROI
                                    </div>
                                </div>
                            </div>
                        )) || (
                            <div className="text-gray-500 text-sm">No agent data available</div>
                        )}
                    </div>
                </div>
            </div>

            {/* Platform Summary Stats */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
                <div className="bg-base-200 rounded-lg p-6">
                    <h3 className="text-lg font-semibold text-gray-400 mb-2">Total Agents</h3>
                    <div className="text-3xl font-bold text-white mb-1">
                        {formatNumber(platformData?.totalAgents || 0)}
                    </div>
                    <div
                        className={`text-sm ${(platformData?.agentsChange24h || 0) >= 0 ? 'text-green-500' : 'text-red-500'}`}>
                        {formatChangeIndicator(platformData?.agentsChange24h || 0)}
                    </div>
                </div>

                <div className="bg-base-200 rounded-lg p-6">
                    <h3 className="text-lg font-semibold text-gray-400 mb-2">Active Strategies</h3>
                    <div className="text-3xl font-bold text-white mb-1">
                        {formatNumber(platformData?.totalActiveStrategies || 0)}
                    </div>
                    <div
                        className={`text-sm ${(platformData?.strategiesChange24h || 0) >= 0 ? 'text-green-500' : 'text-red-500'}`}>
                        {formatChangeIndicator(platformData?.strategiesChange24h || 0)}
                    </div>
                </div>

                <div className="bg-base-200 rounded-lg p-6">
                    <h3 className="text-lg font-semibold text-gray-400 mb-2">Total Platform PnL</h3>
                    <div
                        className={`text-3xl font-bold ${(platformData?.totalPlatformPnL || 0) >= 0 ? 'text-green-500' : 'text-red-500'}`}>
                        {(platformData?.totalPlatformPnL || 0) >= 0 ? '+' : ''}{formatCurrency(platformData?.totalPlatformPnL || 0)}
                    </div>
                    <div
                        className={`text-sm ${(platformData?.pnLChange24h || 0) >= 0 ? 'text-green-500' : 'text-red-500'}`}>
                        {(platformData?.pnLChange24h || 0) >= 0 ? '+' : ''}{formatCurrency(platformData?.pnLChange24h || 0)} Today
                    </div>
                </div>

                <div className="bg-base-200 rounded-lg p-6">
                    <h3 className="text-lg font-semibold text-gray-400 mb-2">Open Interest</h3>
                    <div className="text-3xl font-bold text-white mb-1">
                        {formatCurrency(platformData?.totalOpenInterest || 0)}
                    </div>
                    <div
                        className={`text-sm ${(platformData?.openInterestChange24h || 0) >= 0 ? 'text-green-500' : 'text-red-500'}`}>
                        {(platformData?.openInterestChange24h || 0) >= 0 ? '+' : ''}{formatCurrency(platformData?.openInterestChange24h || 0)} Today
                    </div>
                </div>
            </div>

            {/* Position Metrics */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
                <div className="bg-base-200 rounded-lg p-6">
                    <h3 className="text-lg font-semibold text-gray-400 mb-2">Total Positions</h3>
                    <div className="text-3xl font-bold text-white mb-1">
                        {formatNumber(platformData?.totalPositionCount || 0)}
                    </div>
                    <div
                        className={`text-sm ${(platformData?.positionCountChange24h || 0) >= 0 ? 'text-green-500' : 'text-red-500'}`}>
                        {formatChangeIndicator(platformData?.positionCountChange24h || 0)}
                    </div>
                </div>

                <div className="bg-base-200 rounded-lg p-6">
                    <h3 className="text-lg font-semibold text-gray-400 mb-2">Long Positions</h3>
                    <div className="text-3xl font-bold text-green-400 mb-1">
                        {formatNumber(platformData?.positionCountByDirection?.Long || 0)}
                    </div>
                    <div className="text-sm text-gray-400">
                        {platformData?.totalPositionCount ?
                            ((platformData.positionCountByDirection?.Long || 0) / platformData.totalPositionCount * 100).toFixed(1) : 0}%
                        of total
                    </div>
                </div>

                <div className="bg-base-200 rounded-lg p-6">
                    <h3 className="text-lg font-semibold text-gray-400 mb-2">Short Positions</h3>
                    <div className="text-3xl font-bold text-red-400 mb-1">
                        {formatNumber(platformData?.positionCountByDirection?.Short || 0)}
                    </div>
                    <div className="text-sm text-gray-400">
                        {platformData?.totalPositionCount ?
                            ((platformData.positionCountByDirection?.Short || 0) / platformData.totalPositionCount * 100).toFixed(1) : 0}%
                        of total
                    </div>
                </div>
            </div>

            {/* Volume and Positions by Asset */}
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
                {/* Volume by Asset */}
                <div className="bg-base-200 rounded-lg p-6">
                    <h3 className="text-lg font-semibold text-gray-400 mb-4">Volume by Asset</h3>
                    <div className="space-y-3 max-h-80 overflow-y-auto">
                        {platformData?.volumeByAsset && Object.keys(platformData.volumeByAsset).length > 0 ? (
                            Object.entries(platformData.volumeByAsset)
                                .sort(([, a], [, b]) => b - a)
                                .slice(0, 10)
                                .map(([asset, volume]) => (
                                    <div key={asset} className="flex items-center justify-between">
                                        <div className="flex items-center gap-2">
                                            <div
                                                className="w-8 h-8 bg-blue-500 rounded-full flex items-center justify-center">
                        <span className="text-xs font-bold text-white">
                          {asset.substring(0, 2)}
                        </span>
                                            </div>
                                            <span className="text-white font-medium">{asset}</span>
                                        </div>
                                        <div className="text-right">
                                            <div className="text-white font-semibold">
                                                {formatCurrency(volume)}
                                            </div>
                                        </div>
                                    </div>
                                ))
                        ) : (
                            <div className="text-gray-500 text-sm">No volume data available</div>
                        )}
                    </div>
                </div>

                {/* Positions by Asset */}
                <div className="bg-base-200 rounded-lg p-6">
                    <h3 className="text-lg font-semibold text-gray-400 mb-4">Positions by Asset</h3>
                    <div className="space-y-3 max-h-80 overflow-y-auto">
                        {platformData?.positionCountByAsset && Object.keys(platformData.positionCountByAsset).length > 0 ? (
                            Object.entries(platformData.positionCountByAsset)
                                .sort(([, a], [, b]) => b - a)
                                .slice(0, 10)
                                .map(([asset, count]) => (
                                    <div key={asset} className="flex items-center justify-between">
                                        <div className="flex items-center gap-2">
                                            <div
                                                className="w-8 h-8 bg-purple-500 rounded-full flex items-center justify-center">
                        <span className="text-xs font-bold text-white">
                          {asset.substring(0, 2)}
                        </span>
                                            </div>
                                            <span className="text-white font-medium">{asset}</span>
                                        </div>
                                        <div className="text-right">
                                            <div className="text-white font-semibold">
                                                {formatNumber(count)} positions
                                            </div>
                                            <div className="text-xs text-gray-400">
                                                {platformData?.totalPositionCount ?
                                                    (count / platformData.totalPositionCount * 100).toFixed(1) : 0}% of
                                                total
                                            </div>
                                        </div>
                                    </div>
                                ))
                        ) : (
                            <div className="text-gray-500 text-sm">No position data available</div>
                        )}
                    </div>
                </div>
            </div>

            {/* Data Freshness Indicator */}
            <div className="bg-base-200 rounded-lg p-4">
                <div className="flex items-center justify-between text-sm text-gray-400">
                    <div className="flex items-center gap-4">
                        <div className="flex items-center gap-2">
                            <span>Last updated: {platformData?.lastUpdated ? new Date(platformData.lastUpdated).toLocaleString() : 'Unknown'}</span>
                            {isFetching && (
                                <div className="flex items-center gap-1 text-blue-400">
                                    <div className="loading loading-spinner loading-xs"></div>
                                    <span>Refreshing...</span>
                                </div>
                            )}
                        </div>
                        <button 
                            onClick={handleForceRefresh}
                            disabled={isFetching}
                            className="btn btn-xs btn-outline btn-primary disabled:loading"
                            title="Force refresh data"
                        >
                            {isFetching ? (
                                <>
                                    <span className="loading loading-spinner loading-xs"></span>
                                    Refreshing...
                                </>
                            ) : (
                                <>
                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-3 h-3">
                                        <path strokeLinecap="round" strokeLinejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0 3.181 3.183a8.25 8.25 0 0 0 13.803-3.7M4.031 9.865a8.25 8.25 0 0 1 13.803-3.7l3.181 3.182m0-4.991v4.99" />
                                    </svg>
                                    Refresh
                                </>
                            )}
                        </button>
                    </div>
                    <span>24h snapshot: {platformData?.last24HourSnapshot ? new Date(platformData.last24HourSnapshot).toLocaleString() : 'Unknown'}</span>
                </div>
            </div>
        </div>
    )
}

export default PlatformSummary
