import React, {useEffect, useMemo, useState} from 'react'
import {GridTile} from '../../components/mollecules'
import Table from '../../components/mollecules/Table/Table'
import useApiUrlStore from '../../app/store/apiStore'
import {type AgentSummaryViewModel, DataClient, type PaginatedAgentIndexResponse} from '../../generated/ManagingApi'

const TIME_FILTERS = [
  { label: '24H', value: '24H' },
  { label: '3D', value: '3D' },
  { label: '1W', value: '1W' },
  { label: '1M', value: '1M' },
  { label: '1Y', value: '1Y' },
  { label: 'Total', value: 'Total' },
]

const SORT_OPTIONS = [
  { label: 'Total PnL', value: 'TotalPnL' },
  { label: 'Total ROI', value: 'TotalROI' },
  { label: 'Wins', value: 'Wins' },
  { label: 'Losses', value: 'Losses' },
  { label: 'Agent Name', value: 'AgentName' },
  { label: 'Created At', value: 'CreatedAt' },
  { label: 'Updated At', value: 'UpdatedAt' },
]

function AgentIndex({ index }: { index: number }) {
  const { apiUrl } = useApiUrlStore()
  const [data, setData] = useState<PaginatedAgentIndexResponse | null>(null)
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  
  // Pagination state
  const [currentPage, setCurrentPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  
  // Filter and sort state
  const [timeFilter, setTimeFilter] = useState('Total')
  const [sortBy, setSortBy] = useState('TotalPnL')
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc')
  const [agentNameFilter, setAgentNameFilter] = useState('')

  const fetchData = async () => {
    setIsLoading(true)
    setError(null)
    
    try {
      const client = new DataClient({}, apiUrl)
      const response = await client.data_GetAgentIndexPaginated(
        currentPage,
        pageSize,
        sortBy as any, // Cast to enum type
        sortOrder,
        agentNameFilter || undefined,
      )
      setData(response)
    } catch (err) {
      setError('Failed to fetch agent data. Please try again.')
      console.error('Error fetching agent data:', err)
    } finally {
      setIsLoading(false)
    }
  }

  useEffect(() => {
    fetchData()
  }, [currentPage, pageSize, timeFilter, sortBy, sortOrder, agentNameFilter])

  const handleSort = (columnId: string) => {
    if (sortBy === columnId) {
      setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')
    } else {
      setSortBy(columnId)
      setSortOrder('desc')
    }
  }

  const handlePageChange = (newPage: number) => {
    setCurrentPage(newPage)
  }

  const handleAgentNameFilterChange = (value: string) => {
    setAgentNameFilter(value)
    setCurrentPage(1) // Reset to first page when filtering
  }

  const columns = useMemo(() => [
    {
      Header: 'Agent Name',
      accessor: 'agentName',
      Cell: ({ value }: { value: string }) => (
        <span className="font-medium">{value || 'Unknown'}</span>
      ),
    },
    {
      Header: 'Total PnL',
      accessor: 'totalPnL',
      Cell: ({ value }: { value: number }) => (
        <span className={value >= 0 ? 'text-green-500' : 'text-red-500'}>
          {value >= 0 ? '+' : ''}${value.toLocaleString(undefined, { maximumFractionDigits: 2 })}
        </span>
      ),
    },
    {
      Header: 'Total ROI',
      accessor: 'totalROI',
      Cell: ({ value }: { value: number }) => (
        <span className={value >= 0 ? 'text-green-500' : 'text-red-500'}>
          {value >= 0 ? '+' : ''}{value.toFixed(2)}%
        </span>
      ),
    },
    {
      Header: 'Wins/Losses',
      accessor: 'wins',
      Cell: ({ row }: { row: { original: AgentSummaryViewModel } }) => (
        <span>
          {row.original.wins}/{row.original.losses}
        </span>
      ),
    },
    {
      Header: 'Win Rate',
      accessor: 'averageWinRate',
      Cell: ({ value }: { value: number }) => (
        <span className="font-medium">{value.toFixed(1)}%</span>
      ),
    },
    {
      Header: 'Active Strategies',
      accessor: 'activeStrategiesCount',
      Cell: ({ value }: { value: number }) => (
        <span className="badge badge-primary">{value}</span>
      ),
    },
    {
      Header: 'Total Volume',
      accessor: 'totalVolume',
      Cell: ({ value }: { value: number }) => (
        <span>${value.toLocaleString(undefined, { maximumFractionDigits: 2 })}</span>
      ),
    },
  ], [])

  const tableData = useMemo(() => {
    if (!data?.agentSummaries) return []
    return data.agentSummaries.map(agent => {
      const wins = Number(agent.wins) || 0
      const losses = Number(agent.losses) || 0
      const totalTrades = wins + losses
      const averageWinRate = totalTrades > 0 ? (wins * 100) / totalTrades : 0
      
      return {
        ...agent,
        // Ensure all numeric values are numbers for proper sorting
        totalPnL: Number(agent.totalPnL) || 0,
        totalROI: Number(agent.totalROI) || 0,
        wins,
        losses,
        averageWinRate,
        activeStrategiesCount: Number(agent.activeStrategiesCount) || 0,
        totalVolume: Number(agent.totalVolume) || 0,
      }
    })
  }, [data?.agentSummaries])

  return (
    <div className="container mx-auto pt-6 space-y-6">
      <GridTile title="Agent Index">
        {/* Filters and Controls */}
        <div className="flex flex-wrap gap-4 mb-6">
          <div className="flex items-center gap-2">
            <label className="text-sm font-medium">Agent Name:</label>
            <input
              type="text"
              className="input input-bordered input-sm w-48"
              placeholder="Filter by agent name..."
              value={agentNameFilter}
              onChange={(e) => handleAgentNameFilterChange(e.target.value)}
            />
          </div>

          <div className="flex items-center gap-2">
            <label className="text-sm font-medium">Sort By:</label>
            <select
              className="select select-bordered select-sm"
              value={sortBy}
              onChange={(e) => setSortBy(e.target.value)}
            >
              {SORT_OPTIONS.map(option => (
                <option key={option.value} value={option.value}>
                  {option.label}
                </option>
              ))}
            </select>
          </div>

          <div className="flex items-center gap-2">
            <label className="text-sm font-medium">Order:</label>
            <select
              className="select select-bordered select-sm"
              value={sortOrder}
              onChange={(e) => setSortOrder(e.target.value as 'asc' | 'desc')}
            >
              <option value="desc">Descending</option>
              <option value="asc">Ascending</option>
            </select>
          </div>

          <div className="flex items-center gap-2">
            <label className="text-sm font-medium">Page Size:</label>
            <select
              className="select select-bordered select-sm"
              value={pageSize}
              onChange={(e) => {
                setPageSize(Number(e.target.value))
                setCurrentPage(1) // Reset to first page when changing page size
              }}
            >
              {[10, 20, 50, 100].map(size => (
                <option key={size} value={size}>
                  {size}
                </option>
              ))}
            </select>
          </div>
        </div>

        {/* Loading State */}
        {isLoading && (
          <div className="flex justify-center items-center py-8">
            <span className="loading loading-spinner loading-lg"></span>
            <span className="ml-2">Loading agents...</span>
          </div>
        )}

        {/* Error State */}
        {error && (
          <div className="alert alert-error">
            <span>{error}</span>
          </div>
        )}

        {/* Data Summary */}
        {data && (
          <div className="mb-4 p-4 bg-base-200 rounded-lg">
            <div className="flex justify-between items-center">
              <div>
                <span className="text-sm opacity-70">
                  Showing {data.agentSummaries?.length || 0} of {data.totalCount || 0} agents
                  {agentNameFilter && ` (filtered by "${agentNameFilter}")`}
                </span>
              </div>
              <div className="text-sm opacity-70">
                Page {data.currentPage || 1} of {data.totalPages || 1}
              </div>
            </div>
          </div>
        )}

        {/* Table */}
        {data && data.agentSummaries && data.agentSummaries.length > 0 && (
          <Table
            columns={columns}
            data={tableData}
            showPagination={false} // We'll handle pagination manually
            hiddenColumns={[]}
          />
        )}

        {/* Manual Pagination */}
        {data && data.totalPages && data.totalPages > 1 && (
          <div className="flex justify-center items-center gap-2 mt-4">
            <button
              className="btn btn-sm"
              onClick={() => handlePageChange(1)}
              disabled={currentPage === 1}
            >
              {'<<'}
            </button>
            <button
              className="btn btn-sm"
              onClick={() => handlePageChange(currentPage - 1)}
              disabled={!data.hasPreviousPage}
            >
              {'<'}
            </button>
            
            {/* Page numbers */}
            <div className="flex gap-1">
              {Array.from({ length: Math.min(5, data.totalPages || 1) }, (_, i) => {
                let pageNum
                if ((data.totalPages || 1) <= 5) {
                  pageNum = i + 1
                } else if (currentPage <= 3) {
                  pageNum = i + 1
                } else if (currentPage >= (data.totalPages || 1) - 2) {
                  pageNum = (data.totalPages || 1) - 4 + i
                } else {
                  pageNum = currentPage - 2 + i
                }
                
                return (
                  <button
                    key={pageNum}
                    className={`btn btn-sm ${currentPage === pageNum ? 'btn-primary' : ''}`}
                    onClick={() => handlePageChange(pageNum)}
                  >
                    {pageNum}
                  </button>
                )
              })}
            </div>
            
            <button
              className="btn btn-sm"
              onClick={() => handlePageChange(currentPage + 1)}
              disabled={!data.hasNextPage}
            >
              {'>'}
            </button>
            <button
              className="btn btn-sm"
              onClick={() => handlePageChange(data.totalPages || 1)}
              disabled={currentPage === data.totalPages}
            >
              {'>>'}
            </button>
          </div>
        )}

        {/* No Data State */}
        {data && (!data.agentSummaries || data.agentSummaries.length === 0) && !isLoading && (
          <div className="text-center py-8">
            <p>
              {agentNameFilter 
                ? `No agents found matching "${agentNameFilter}".` 
                : 'No agents found for the selected criteria.'
              }
            </p>
            {agentNameFilter && (
              <button 
                className="btn btn-sm btn-outline mt-2"
                onClick={() => handleAgentNameFilterChange('')}
              >
                Clear Filter
              </button>
            )}
          </div>
        )}
      </GridTile>
    </div>
  )
}

export default AgentIndex 