import React, {useEffect, useState} from 'react'
import type {ClosePositionRequest, Position, UserStrategyDetailsViewModel} from '../../../generated/ManagingApi'
import {BotClient, DataClient} from '../../../generated/ManagingApi'
import useApiUrlStore from '../../../app/store/apiStore'
import Modal from '../Modal/Modal'
import Toast from '../Toast/Toast'

interface TradesModalProps {
  showModal: boolean
  agentName: string | null
  strategyName: string | null
  onClose: () => void
}

const TradesModal: React.FC<TradesModalProps> = ({
  showModal,
  strategyName,
  agentName,
  onClose,
}) => {
  const { apiUrl } = useApiUrlStore()
  const [strategyData, setStrategyData] = useState<UserStrategyDetailsViewModel | null>(null)
  const [loading, setLoading] = useState<boolean>(false)
  const [closingPosition, setClosingPosition] = useState<string | null>(null)

  useEffect(() => {
    console.log('strategyName', strategyName)
    console.log('agentName', agentName)
    if (showModal && strategyName && agentName) {
      fetchStrategyData()
    }
  }, [showModal, strategyName, agentName])

  const fetchStrategyData = async () => {
    if (!strategyName || !agentName) return
    
    setLoading(true)
    const client = new DataClient({}, apiUrl)
    
    try {
      const data = await client.data_GetUserStrategy(agentName, strategyName)
      setStrategyData(data)
    } catch (error) {
      console.error('Error fetching strategy data:', error)
      const errorToast = new Toast('Failed to fetch strategy data', false)
      errorToast.update('error', 'Failed to fetch strategy data')
    } finally {
      setLoading(false)
    }
  }

  const closePosition = async (position: Position) => {
    if (!agentName) return
    
    try {
      setClosingPosition(position.identifier)
      
      const loadingToast = new Toast(`Closing trade ${position.identifier}...`, true)
      
      // Use BotClient instead of fetch
      const botClient = new BotClient({}, apiUrl)
      const request: ClosePositionRequest = {
        identifier: position.initiatorIdentifier,
        positionId: position.identifier
      }
      
      await botClient.bot_ClosePosition(request)
      
      loadingToast.update('success', 'Trade closed successfully!')
      // Refresh data after closing
      fetchStrategyData()
    } catch (error) {
      console.error('Error closing position:', error)
      const errorToast = new Toast('Failed to close trade', false)
      errorToast.update('error', `Failed to close trade: ${error instanceof Error ? error.message : 'Unknown error'}`)
    } finally {
      setClosingPosition(null)
    }
  }

  return (
    <Modal
      showModal={showModal}
      onClose={onClose}
      titleHeader={`Trades for ${strategyName}`}
    >
      <div className="mt-4">
        {loading ? (
          <div className="flex justify-center">
            <div className="loading loading-spinner loading-lg"></div>
          </div>
        ) : strategyData ? (
          <div>
            <div className="mb-4">
              <p className="font-bold">Strategy: {strategyData.name}</p>
              <p>Win Rate: {strategyData.winRate?.toFixed(2)}%</p>
              <p>PnL: {strategyData.pnL?.toFixed(2)} $</p>
              <p>Wins: {strategyData.wins} / Losses: {strategyData.losses}</p>
              <p>Total Volume Traded: {strategyData.totalVolumeTraded?.toFixed(2)} $</p>
              <p>Volume Last 24H: {strategyData.volumeLast24H?.toFixed(2)} $</p>
            </div>
            
            <div className="overflow-x-auto">
              <table className="table table-compact w-full">
                <thead>
                  <tr>
                    <th>Date</th>
                    <th>Direction</th>
                    <th>Status</th>
                    <th>Entry Price</th>
                    <th>Quantity</th>
                    <th>PnL</th>
                    <th>Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {strategyData.positions && strategyData.positions.length > 0 ? (
                    strategyData.positions.map((position: Position) => (
                      <tr key={position.identifier}>
                        <td>{new Date(position.date).toLocaleString()}</td>
                        <td className={position.originDirection === 'Long' ? 'text-success' : 'text-error'}>
                          {position.originDirection}
                        </td>
                        <td>{position.status}</td>
                        <td>{position.Open.price.toFixed(2)}</td>
                        <td>{position.Open.quantity.toFixed(4)}</td>
                        <td className={position.ProfitAndLoss?.realized && position.ProfitAndLoss.realized > 0 ? 'text-success' : 'text-error'}>
                          {position.ProfitAndLoss?.realized?.toFixed(2) || '0.00'} $
                        </td>
                        <td>
                          {position.status !== 'Finished' && (
                            <button 
                              className="btn btn-xs btn-error" 
                              onClick={() => closePosition(position)}
                              disabled={closingPosition === position.identifier}
                            >
                              {closingPosition === position.identifier ? (
                                <span className="loading loading-spinner loading-xs"></span>
                              ) : (
                                'Close'
                              )}
                            </button>
                          )}
                        </td>
                      </tr>
                    ))
                  ) : (
                    <tr>
                      <td colSpan={7} className="text-center">No trades found</td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          </div>
        ) : (
          <p className="text-center">No data available</p>
        )}
      </div>
    </Modal>
  )
}

export default TradesModal 