import React, {useState} from 'react'
import {Card, FormInput, GridTile, Table} from '../../components/mollecules'
import useApiUrlStore from '../../app/store/apiStore'
import Plot from 'react-plotly.js'
import useTheme from '../../hooks/useTheme'
import {
  type AgentBalanceHistory,
  BotStatus,
  DataClient,
  PositionStatus,
  type PositionViewModel,
  TradeDirection,
  type UserStrategyDetailsViewModel
} from '../../generated/ManagingApi'

interface AgentData {
  strategies: UserStrategyDetailsViewModel[]
  balances: AgentBalanceHistory | null
  positions: PositionViewModel[]
}


function AgentSearch({ index }: { index: number }) {
  const { apiUrl } = useApiUrlStore()
  const [agentName, setAgentName] = useState('')
  const [agentData, setAgentData] = useState<AgentData | null>(null)
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const searchAgent = async () => {
    if (!agentName.trim()) return
    
    setIsLoading(true)
    setError(null)
    
    try {
      const client = new DataClient({}, apiUrl)
      
      // Fetch data for a longer period to support all filters
      const startDate = new Date(Date.now() - 365 * 24 * 60 * 60 * 1000) // Last year
      
      // Fetch agent strategies and balances in parallel
      const [strategies, balances] = await Promise.all([
        client.data_GetUserStrategies(agentName.trim()),
        client.data_GetAgentBalances(
          agentName.trim(), 
          startDate,
          new Date()
        )
      ])
      
      // Extract positions from all strategies (status not available in generated PositionViewModel)
      const allPositions = strategies.flatMap(strategy => strategy.positions || [])

      setAgentData({ strategies, balances, positions: allPositions })
    } catch (err) {
      setError('Failed to fetch agent data. Please check the agent name and try again.')
      console.error('Error fetching agent data:', err)
    } finally {
      setIsLoading(false)
    }
  }

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      searchAgent()
    }
  }


  // Calculate current total balance
  const getCurrentBalance = () => {
    const balances = agentData?.balances?.agentBalances
    if (!balances || balances.length === 0) return null
    
    // Get the most recent balance
    const latestBalance = balances[balances.length - 1]
    return {
      totalBalanceValue: latestBalance.totalBalanceValue || 0,
      usdcWalletValue: latestBalance.usdcWalletValue || 0,
      usdcInPositionsValue: latestBalance.usdcInPositionsValue || 0,
      botsAllocation: latestBalance.botsAllocationUsdValue || 0,
    }
  }


  // Calculate summary statistics from strategies
  const calculateSummary = () => {
    if (!agentData?.strategies.length) return null
    
    console.log(agentData.strategies)
    const totalPnL = agentData.strategies.reduce((sum, strategy) => sum + (strategy.pnL || 0), 0)
    const totalNetPnL = agentData.strategies.reduce((sum, strategy) => sum + (strategy.netPnL || 0), 0)
    const totalVolume = agentData.strategies.reduce((sum, strategy) => sum + (strategy.totalVolumeTraded || 0), 0)
    const totalWins = agentData.strategies.reduce((sum, strategy) => sum + (strategy.wins || 0), 0)
    const totalLosses = agentData.strategies.reduce((sum, strategy) => sum + (strategy.losses || 0), 0)
    const totalRuntimeSeconds = agentData.strategies.reduce((sum, strategy) => sum + (strategy.totalRuntimeSeconds || 0), 0)
    const avgWinRate = agentData.strategies.length > 0 
      ? agentData.strategies.reduce((sum, strategy) => sum + (strategy.winRate || 0), 0) / agentData.strategies.length 
      : 0
    
    return {
      totalPnL,
      totalNetPnL,
      totalVolume,
      totalWins,
      totalLosses,
      avgWinRate,
      totalRuntimeSeconds,
      activeStrategies: agentData.strategies.filter(s => s.state === BotStatus.Running).length,
      totalStrategies: agentData.strategies.length
    }
  }

  // Format position time ago
  const formatTimeAgo = (date: Date) => {
    const now = new Date()
    const diffMs = now.getTime() - new Date(date).getTime()
    const diffHours = Math.floor(diffMs / (1000 * 60 * 60))
    const diffDays = Math.floor(diffHours / 24)
    
    if (diffDays > 0) {
      return `${diffDays}day${diffDays > 1 ? 's' : ''} ago`
    } else if (diffHours > 0) {
      return `${diffHours}hour${diffHours > 1 ? 's' : ''} ago`
    } else {
      const diffMinutes = Math.floor(diffMs / (1000 * 60))
      return `${diffMinutes}minute${diffMinutes > 1 ? 's' : ''} ago`
    }
  }

  // Prepare chart data for balance history
  const prepareChartData = () => {
    const balances = agentData?.balances?.agentBalances
    if (!balances || balances.length === 0) return null

    // Sort by time to ensure proper chronological order
    const sortedBalances = [...balances].sort((a, b) => 
      new Date(a.time || 0).getTime() - new Date(b.time || 0).getTime()
    )

    const dates = sortedBalances.map(balance => new Date(balance.time || 0))
    const totalBalanceValues = sortedBalances.map(balance => balance.totalBalanceValue || 0)
    const usdcWalletValues = sortedBalances.map(balance => balance.usdcWalletValue || 0)
    const usdcInPositionsValues = sortedBalances.map(balance => balance.usdcInPositionsValue || 0)
    const botsAllocationValues = sortedBalances.map(balance => balance.botsAllocationUsdValue || 0)
    const pnlValues = sortedBalances.map(balance => balance.pnL || 0)

    return {
      dates,
      totalBalanceValues,
      usdcWalletValues,
      usdcInPositionsValues,
      botsAllocationValues,
      pnlValues
    }
  }

  const summary = calculateSummary()
  const currentBalance = getCurrentBalance()
  const chartData = prepareChartData()
  const theme = useTheme().themeProperty()
  const openPositions = (agentData?.positions || []).filter(p => [
    PositionStatus.Updating,
    PositionStatus.Filled,
    PositionStatus.Flipped
  ].includes(p.status))
  const allPositions = agentData?.positions || []

  const positionTableColumns = React.useMemo(
    () => [
      {
        Header: 'Date',
        accessor: (row: PositionViewModel) => new Date(row.date).toLocaleString(),
      },
      {
        Header: 'Ticker',
        accessor: (row: PositionViewModel) => `${row.ticker}/USDC`,
      },
      {
        Header: 'Direction',
        accessor: (row: PositionViewModel) => row.originDirection,
      },
        {
        Header: 'Leverage',
        accessor: (row: PositionViewModel) => `${row.Open?.leverage ?? 0}x`,
      },
      {
        Header: 'Quantity',
        accessor: (row: PositionViewModel) => row.Open?.quantity ?? 0,
      },
      {
        Header: 'Entry Price',
        accessor: (row: PositionViewModel) => row.Open?.price ?? 0,
      },
      {
        Header: 'Status',
        accessor: (row: PositionViewModel) => row.status,
      },
      {
        Header: 'Realized PnL ($)',
        accessor: (row: PositionViewModel) => row.ProfitAndLoss?.realized ?? 0,
        Cell: ({ value }: { value: number }) => (
          <span className={value >= 0 ? 'text-green-500' : 'text-red-500'}>
            {value >= 0 ? '+' : ''}{value.toFixed(2)}
          </span>
        )
      },
      {
        Header: 'ROI %',
        accessor: (row: PositionViewModel) => {
          const costBasis = (row.Open?.price ?? 0) * (row.Open?.quantity ?? 0)
          if (!costBasis) return 0
          const realized = row.ProfitAndLoss?.realized ?? 0
          return (realized / costBasis) * 100
        },
        Cell: ({ value }: { value: number }) => (
          <span className={value >= 0 ? 'text-green-500' : 'text-red-500'}>
            {value >= 0 ? '+' : ''}{value.toFixed(2)}%
          </span>
        )
      },
    ],
    []
  )

  return (
    <div className="container mx-auto pt-6 space-y-6">
      <GridTile title="Agent Search">
        <div className="flex gap-4 items-end">
          <div className="flex-1">
            <FormInput
              label="Agent Name"
              htmlFor="agentName"
            >
              <input
                id="agentName"
                type="text"
                className="input input-bordered w-full"
                value={agentName}
                onChange={(e: React.ChangeEvent<HTMLInputElement>) => setAgentName(e.target.value)}
                onKeyPress={handleKeyPress}
                placeholder="Enter agent name to search..."
              />
            </FormInput>
          </div>
          <button 
            className="btn btn-primary"
            onClick={searchAgent}
            disabled={isLoading || !agentName.trim()}
          >
            {isLoading ? (
              <>
                <span className="loading loading-spinner loading-xs"></span>
                Searching...
              </>
            ) : (
              'Search'
            )}
          </button>
        </div>
        
        {error && (
          <div className="alert alert-error mt-4">
            <span>{error}</span>
          </div>
        )}
      </GridTile>

      {/* Open Positions Section */}
      {openPositions.length > 0 && (
        <GridTile title="Open Positions">
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {openPositions.map((position, index) => (
              <div key={index} className="bg-base-200 p-4 rounded-lg border border-base-300">
                <div className="flex justify-between items-start mb-3">
                  <div>
                    <h3 className="text-lg font-bold">{position.ticker}/USDC</h3>
                    <div className="text-sm opacity-70">{formatTimeAgo(position.date)}</div>
                  </div>
                </div>
                
                <div className="mb-3">
                  <span className={`text-sm font-medium ${
                    position.originDirection === TradeDirection.Long ? 'text-green-500' : 'text-red-500'
                  }`}>
                    {position.originDirection === TradeDirection.Long ? 'Long' : 'Short'} {position.Open.leverage}x
                  </span>
                </div>
                
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <span className={`text-lg font-bold ${
                      (position.ProfitAndLoss?.realized || 0) >= 0 ? 'text-green-500' : 'text-red-500'
                    }`}>
                      {(position.ProfitAndLoss?.realized || 0) >= 0 ? '+' : ''}${(position.ProfitAndLoss?.realized || 0).toFixed(2)}
                    </span>
                    <span className={`flex items-center gap-1 text-sm ${
                      (position.ProfitAndLoss?.realized || 0) >= 0 ? 'text-green-500' : 'text-red-500'
                    }`}>
                      {(position.ProfitAndLoss?.realized || 0) >= 0 ? '↑' : '↓'}
                      {Math.abs(((position.ProfitAndLoss?.realized || 0) / (position.Open?.price * position.Open?.quantity || 1)) * 100).toFixed(2)}%
                    </span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </GridTile>
      )}

      {summary && (
        <GridTile title={`Agent Stats - ${agentName}`}>

          {/* Current Balance Display */}
          {currentBalance && (
            <div className="mb-6 p-4 bg-primary/10 rounded-lg border border-primary/20">
              <h3 className="text-lg font-semibold mb-2">Current Balance</h3>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                <div>
                  <div className="text-sm opacity-70">Total Balance Value</div>
                  <div className="text-2xl font-bold">${currentBalance.totalBalanceValue.toLocaleString(undefined, { maximumFractionDigits: 2 })}</div>
                </div>
                <div>
                  <div className="text-sm opacity-70">USDC in Wallet</div>
                  <div className="text-xl font-semibold text-blue-500">${currentBalance.usdcWalletValue.toLocaleString(undefined, { maximumFractionDigits: 2 })}</div>
                </div>
                <div>
                  <div className="text-sm opacity-70">USDC in Positions</div>
                  <div className="text-xl font-semibold text-green-500">${currentBalance.usdcInPositionsValue.toLocaleString(undefined, { maximumFractionDigits: 2 })}</div>
                </div>
                <div>
                  <div className="text-sm opacity-70">Bots Allocation</div>
                  <div className="text-xl font-semibold">${currentBalance.botsAllocation.toLocaleString(undefined, { maximumFractionDigits: 2 })}</div>
                </div>
              </div>
            </div>
          )}

          {/* Balance History Chart */}
          {chartData && (
            <div className="mb-6 p-4 bg-primary/10 rounded-lg border border-primary/20">
              <h3 className="text-lg font-semibold mb-4">Balance History</h3>
              <Plot
                data={[
                  {
                    x: chartData.dates,
                    y: chartData.totalBalanceValues,
                    type: 'scatter' as const,
                    mode: 'lines+markers' as const,
                    name: 'Total Balance Value',
                    line: { color: theme.primary, width: 3 },
                    marker: { size: 6 }
                  },
                  {
                    x: chartData.dates,
                    y: chartData.usdcWalletValues,
                    type: 'scatter' as const,
                    mode: 'lines+markers' as const,
                    name: 'USDC in Wallet',
                    line: { color: '#3b82f6', width: 2 },
                    marker: { size: 5 }
                  },
                  {
                    x: chartData.dates,
                    y: chartData.usdcInPositionsValues,
                    type: 'scatter' as const,
                    mode: 'lines+markers' as const,
                    name: 'USDC in Positions',
                    line: { color: '#10b981', width: 2 },
                    marker: { size: 5 }
                  },
                  {
                    x: chartData.dates,
                    y: chartData.botsAllocationValues,
                    type: 'scatter' as const,
                    mode: 'lines+markers' as const,
                    name: 'Bots Allocation',
                    line: { color: theme.success, width: 2 },
                    marker: { size: 5 }
                  },
                  {
                    x: chartData.dates,
                    y: chartData.pnlValues,
                    type: 'scatter' as const,
                    mode: 'lines+markers' as const,
                    name: 'PnL',
                    line: { color: theme.warning, width: 2 },
                    marker: { size: 5 }
                  }
                ]}
                layout={{
                  title: {
                    text: 'Agent Balance Trends Over Time',
                    font: { color: theme.neutral }
                  },
                  xaxis: {
                    title: {
                      text: 'Date',
                      font: { color: theme.neutral }
                    },
                    color: theme.neutral,
                    gridcolor: theme.accent
                  },
                  yaxis: {
                    title: {
                      text: 'Value (USD)',
                      font: { color: theme.neutral }
                    },
                    color: theme.neutral,
                    gridcolor: theme.accent
                  },
                  plot_bgcolor: 'transparent',
                  paper_bgcolor: 'transparent',
                  font: { color: theme.neutral },
                  legend: {
                    font: { color: theme.neutral }
                  },
                  margin: { t: 50, r: 50, b: 50, l: 50 },
                  hovermode: 'x unified'
                }}
                config={{
                  displayModeBar: true,
                  displaylogo: false,
                  modeBarButtonsToRemove: ['pan2d', 'lasso2d', 'select2d']
                }}
                style={{ width: '100%', height: '400px' }}
              />
            </div>
          )}

          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <Card name="Total Volume Traded">
              <div className="stat">
                <div className="stat-title text-xs">Total Volume Traded</div>
                <div className="stat-value text-lg">${summary.totalVolume.toLocaleString(undefined, { maximumFractionDigits: 2 })}</div>
                <div className="stat-desc text-xs">All time trading volume</div>
              </div>
            </Card>

            <Card name="Win / Loss">
              <div className="stat">
                <div className="stat-title text-xs">Win / Loss</div>
                <div className="stat-value text-lg">{summary.totalWins}/{summary.totalLosses}</div>
                <div className="stat-desc text-xs">{summary.avgWinRate.toFixed(0)}% Avg Winrate</div>
              </div>
            </Card>


            <Card name="Active Strategies">
              <div className="stat">
                <div className="stat-title text-xs">Strategies</div>
                <div className="stat-value text-lg">{summary.activeStrategies}/{summary.totalStrategies}</div>
                <div className="stat-desc text-xs">Active / Total</div>
              </div>
            </Card>

            <Card name="ROI">
              <div className="stat">
                <div className="stat-title text-xs">ROI</div>
                <div className="stat-value text-lg">
                  <span className={summary.totalNetPnL >= 0 ? 'text-green-500' : 'text-red-500'}>
                    {((summary.totalNetPnL / (summary.totalVolume || 1)) * 100).toFixed(2)}%
                  </span>
                </div>
                <div className="stat-desc text-xs">Return on Investment</div>
              </div>
            </Card>

            <Card name="Total PnL">
              <div className="stat">
                <div className="stat-title text-xs">Total PnL</div>
                <div className="stat-value text-lg">
                  <span className={summary.totalPnL >= 0 ? 'text-green-500' : 'text-red-500'}>
                    {summary.totalPnL >= 0 ? '+' : ''}${summary.totalPnL.toLocaleString(undefined, { maximumFractionDigits: 2 })}
                  </span>
                </div>
                <div className="stat-desc text-xs">
                  Net: <span className={summary.totalNetPnL >= 0 ? 'text-green-500' : 'text-red-500'}>
                    {summary.totalNetPnL >= 0 ? '+' : ''}${summary.totalNetPnL.toLocaleString(undefined, { maximumFractionDigits: 2 })}
                  </span>
                </div>
              </div>
            </Card>

            <Card name="Total Fees">
              <div className="stat">
                <div className="stat-title text-xs">Total Fees</div>
                <div className="stat-value text-lg text-orange-500">
                  ${(summary.totalPnL - summary.totalNetPnL).toLocaleString(undefined, { maximumFractionDigits: 2 })}
                </div>
                <div className="stat-desc text-xs">Fees paid across all strategies</div>
              </div>
            </Card>

          <Card name="Total Runtime">
            <div className="stat">
              <div className="stat-title text-xs">Total Runtime</div>
              <div className="stat-value text-lg">
                {(() => {
                  const totalSeconds = summary.totalRuntimeSeconds || 0
                  const days = Math.floor(totalSeconds / 86400)
                  const hours = Math.floor((totalSeconds % 86400) / 3600)
                  const minutes = Math.floor((totalSeconds % 3600) / 60)
                  if (days > 0) {
                    return `${days}d ${hours}h`
                  } else if (hours > 0) {
                    return `${hours}h ${minutes}m`
                  } else {
                    return `${minutes}m`
                  }
                })()}
              </div>
              <div className="stat-desc text-xs">Across all strategies</div>
            </div>
          </Card>
          </div>
        </GridTile>
      )}

      {agentData?.strategies && agentData.strategies.length > 0 && (
        <GridTile title="Strategies">
          <div className="space-y-4">
            <div className="grid grid-cols-7 gap-4 p-3 bg-base-300 rounded-lg text-sm font-medium">
              <span>Name</span>
              <span>Ticker</span>
              <span>Status</span>
              <span>Net PnL</span>
              <span>ROI</span>
              <span>Runtime</span>
              <span>Avg Winrate</span>
            </div>
            
            {agentData.strategies.map((strategy, index) => (
              <div key={index} className="grid grid-cols-7 gap-4 p-3 bg-base-200 rounded-lg text-sm">
                <span className="font-medium">{strategy.name}</span>
                <span className="text-blue-500 font-medium">{strategy.ticker || '-'}</span>
                <span className={`badge ${strategy.state == BotStatus.Running ? 'badge-success' : 'badge-warning'}`}>
                  {strategy.state}
                </span>
                <span className={strategy.netPnL && strategy.netPnL >= 0 ? 'text-green-500' : 'text-red-500'}>
                  {strategy.netPnL && strategy.netPnL >= 0 ? '+' : ''}${(strategy.netPnL || 0).toFixed(2)}
                </span>
                <span className={strategy.roiPercentage && strategy.roiPercentage >= 0 ? 'text-green-500' : 'text-red-500'}>
                  {strategy.roiPercentage && strategy.roiPercentage >= 0 ? '+' : ''}{(strategy.roiPercentage || 0).toFixed(2)}%
                </span>
                <span>
                  {strategy.totalRuntimeSeconds && strategy.totalRuntimeSeconds > 0 ? (() => {
                    const totalSeconds = strategy.totalRuntimeSeconds
                    const days = Math.floor(totalSeconds / 86400)
                    const hours = Math.floor((totalSeconds % 86400) / 3600)
                    const minutes = Math.floor((totalSeconds % 3600) / 60)
                    if (days > 0) {
                      return `${days}d ${hours}h`
                    } else if (hours > 0) {
                      return `${hours}h ${minutes}m`
                    } else {
                      return `${minutes}m`
                    }
                  })() : '-'}
                  {strategy.state === BotStatus.Running && <span className="ml-1 text-green-500">●</span>}
                </span>
                <span>{(strategy.winRate || 0).toFixed(0)}%</span>
              </div>
            ))}
          </div>
        </GridTile>
      )}

      {agentData && agentData.strategies.length === 0 && (
        <GridTile title="No Data">
          <div className="text-center py-8">
            <p>No strategies found for agent "{agentName}"</p>
          </div>
        </GridTile>
      )}

      {allPositions.length > 0 && (
        <GridTile title="All Positions">
          <Table
            columns={positionTableColumns}
            data={allPositions}
            showPagination={true}
          />
        </GridTile>
      )}
    </div>
  )
}

export default AgentSearch 