import {ViewGridAddIcon} from '@heroicons/react/solid'
import React, {useState} from 'react'
import 'react-toastify/dist/ReactToastify.css'
import useApiUrlStore from '../../app/store/apiStore'
import {UnifiedTradingModal} from '../../components/organism'
import {BotClient, BotStatus, UserClient} from '../../generated/ManagingApi'

import BotList from './botList'
import {useQuery} from '@tanstack/react-query'

const Bots: React.FC = () => {
  const [activeTab, setActiveTab] = useState(0)
  const [showBotConfigModal, setShowBotConfigModal] = useState(false)
  const [pageNumber, setPageNumber] = useState(1)
  const [pageSize] = useState(50) // Fixed page size for now

  // Reset page number when tab changes
  const handleTabChange = (newTab: number) => {
    setActiveTab(newTab)
    setPageNumber(1) // Reset to first page when changing tabs
  }
  const { apiUrl } = useApiUrlStore()
  const botClient = new BotClient({}, apiUrl)
  const userClient = new UserClient({}, apiUrl)

  const { data: currentUser } = useQuery({
    queryFn: () => userClient.user_GetCurrentUser(),
    queryKey: ['currentUser'],
  })

  // Query for paginated bots using the new endpoint
  const { data: paginatedBots } = useQuery({
    queryFn: () => {
      switch (activeTab) {
        case 0: // All Active Bots
          return botClient.bot_GetBotsPaginated(pageNumber, pageSize, BotStatus.Running, undefined, undefined, undefined, 'CreatedAt', 'Desc')
        case 1: // My Active Bots
          return botClient.bot_GetBotsPaginated(pageNumber, pageSize, BotStatus.Running, undefined, undefined, currentUser?.agentName, 'CreatedAt', 'Desc')
        case 2: // My Down Bots
          return botClient.bot_GetBotsPaginated(pageNumber, pageSize, BotStatus.Stopped, undefined, undefined, currentUser?.agentName, 'CreatedAt', 'Desc')
        case 3: // Saved Bots
          return botClient.bot_GetBotsPaginated(pageNumber, pageSize, BotStatus.Saved, undefined, undefined, currentUser?.agentName, 'CreatedAt', 'Desc')
        default:
          return botClient.bot_GetBotsPaginated(pageNumber, pageSize, undefined, undefined, undefined, undefined, 'CreatedAt', 'Desc')
      }
    },
    queryKey: ['paginatedBots', activeTab, pageNumber, pageSize, currentUser?.agentName],
    enabled: !!currentUser,
  })

  const filteredBots = paginatedBots?.items || []

  function openCreateBotModal() {
    setShowBotConfigModal(true)
  }


  const tabs = [
    { label: 'All Active Bots', index: 0 },
    { label: 'My Active Bots', index: 1 },
    { label: 'My Down Bots', index: 2 },
    { label: 'Saved Bots', index: 3 },
  ]

  return (
    <div>
      <div className="container mx-auto">
        {/* Action Buttons */}
        <div className="flex gap-2 mb-4">
          <div className="tooltip" data-tip="Create new bot">
            <button className="btn btn-primary m-1 text-xs" onClick={openCreateBotModal}>
              <ViewGridAddIcon width="20"></ViewGridAddIcon>
            </button>
          </div>
        </div>

        {/* Tabs */}
        <div className="tabs tabs-boxed mb-4">
          {tabs.map((tab) => (
            <button
              key={tab.index}
              className={`tab ${activeTab === tab.index ? 'tab-active' : ''}`}
              onClick={() => handleTabChange(tab.index)}
            >
              {tab.label}
            </button>
          ))}
        </div>

        {/* Bot List */}
        <BotList list={filteredBots} />

        {/* Unified Trading Modal */}
        <UnifiedTradingModal
          mode="createBot"
          showModal={showBotConfigModal}
          closeModal={() => {
            setShowBotConfigModal(false)
          }}
        />
      </div>
    </div>
  )
}

export default Bots
