import React, {useEffect, useState} from 'react'

import useApiUrlStore from '../../../app/store/apiStore'
import type {PlatformSummaryViewModel, TradingBotResponse} from '../../../generated/ManagingApi'
import {DataClient} from '../../../generated/ManagingApi'

// Time filter options matching backend
const TIME_FILTERS = ['24H', '3D', '1W', '1M', '1Y', 'Total']

function GetGlobalWinrate(bots: TradingBotResponse[]) {
    if (bots == null || bots == undefined || bots.length == 0) {
        return 0
    }

    return bots.reduce((acc, bot) => {
        return acc + bot.winRate
    }, 0) / bots.length
}

const Summary: React.FC<{ bots: TradingBotResponse[] }> = ({bots}) => {
    const [globalPnl, setGlobalPnl] = useState<number>(0)
    const [globalWinrate, setGlobalWinrate] = useState<number>(0)
    const [selectedTimeFilter, setSelectedTimeFilter] = useState<string>('Total')
    const [platformStats, setPlatformStats] = useState<PlatformSummaryViewModel | null>(null)
    const [isLoading, setIsLoading] = useState<boolean>(false)

    const {apiUrl} = useApiUrlStore()

    useEffect(() => {
        if (bots) {
            const pnl = bots.reduce((acc, bot) => {
                return acc + bot.profitAndLoss
            }, 0)
            setGlobalPnl(pnl)
            setGlobalWinrate(GetGlobalWinrate(bots))

        }
    }, [bots])

    // Fetch platform summary data
    useEffect(() => {
        const fetchPlatformStats = async () => {
            setIsLoading(true)
            try {
                const dataClient = new DataClient({}, apiUrl)
                const data = await dataClient.data_GetPlatformSummary(selectedTimeFilter)
                setPlatformStats(data)
            } catch (error) {
                console.error('Error fetching platform stats:', error)
            } finally {
                setIsLoading(false)
            }
        }

        fetchPlatformStats()
    }, [apiUrl, selectedTimeFilter])

    return (
        <div className="p-4">
            <div className="mb-4 flex justify-between items-center">
                <h2 className="text-xl font-bold">Platform Overview</h2>
                <div className="join">
                    {TIME_FILTERS.map((filter) => (
                        <button
                            key={filter}
                            className={`btn btn-sm join-item ${selectedTimeFilter === filter ? 'btn-primary' : 'btn-ghost'}`}
                            onClick={() => setSelectedTimeFilter(filter)}
                        >
                            {filter}
                        </button>
                    ))}
                </div>
            </div>

            <div className="stats bg-primary text-primary-content mb-4">
                <div className="stat">
                    <div className="stat-title">Total Agents</div>
                    <div className="stat-value">{platformStats?.totalAgents ?? 0}</div>
                </div>

                <div className="stat">
                    <div className="stat-title">Active Strategies</div>
                    <div className="stat-value">{platformStats?.totalActiveStrategies ?? 0}</div>
                </div>

                <div className="stat">
                    <div className="stat-title">Total Platform PnL</div>
                    <div className="stat-value">{(platformStats?.totalPlatformPnL ?? 0).toFixed(2)} $</div>
                </div>

                <div className="stat">
                    <div className="stat-title">Volume (Total)</div>
                    <div className="stat-value">{(platformStats?.totalPlatformVolume ?? 0).toFixed(2)} $</div>
                </div>

                <div className="stat">
                    <div className="stat-title">Volume (24h)</div>
                    <div className="stat-value">{(platformStats?.totalPlatformVolumeLast24h ?? 0).toFixed(2)} $</div>
                </div>
            </div>

            <div className="stats bg-primary text-primary-content">
                <div className="stat">
                    <div className="stat-title">Bots running</div>
                    <div className="stat-value">{bots.length}</div>
                </div>

                <div className="stat">
                    <div className="stat-title">Total Profit</div>
                    <div className="stat-value">{globalPnl.toFixed(4)} $</div>
                </div>

                <div className="stat">
                    <div className="stat-title">Global Winrate</div>
                    <div className="stat-value">
                        {globalWinrate ? globalWinrate.toFixed(2) : 0} %
                    </div>
                </div>
            </div>
        </div>
    )
}

export default Summary
