import {ColorSwatchIcon, TrashIcon} from '@heroicons/react/solid'
import {useQuery, useQueryClient} from '@tanstack/react-query'
import React, {useEffect, useState} from 'react'

import 'react-toastify/dist/ReactToastify.css'
import useApiUrlStore from '../../app/store/apiStore'
import {Loader, Slider} from '../../components/atoms'
import {Modal, Toast} from '../../components/mollecules'
import {BacktestTable, UnifiedTradingModal} from '../../components/organism'
import type {LightBacktestResponse} from '../../generated/ManagingApi'
import {BacktestClient} from '../../generated/ManagingApi'

const PAGE_SIZE = 50

const BacktestScanner: React.FC = () => {
  const [showModal, setShowModal] = useState(false)
  const [showModalRemoveBacktest, setShowModalRemoveBacktest] = useState(false)
  const [filteredCount, setFilteredCount] = useState(0)
  const [filterValues, setFilterValues] = useState({
    winRate: 50,
    score: 50
  })
  const [currentPage, setCurrentPage] = useState(1)
  const [currentSort, setCurrentSort] = useState<{ sortBy: string; sortOrder: 'asc' | 'desc' }>({
    sortBy: 'score',
    sortOrder: 'desc'
  })

  const { apiUrl } = useApiUrlStore()
  const queryClient = useQueryClient()
  const backtestClient = new BacktestClient({}, apiUrl)

  // Use TanStack Query for fetching backtests
  const {
    data: backtestData,
    isLoading,
    error,
    refetch
  } = useQuery({
    queryKey: ['backtests', currentPage, currentSort.sortBy, currentSort.sortOrder],
    queryFn: async () => {
      const response = await backtestClient.backtest_GetBacktestsPaginated(
        currentPage, 
        PAGE_SIZE, 
        currentSort.sortBy, 
        currentSort.sortOrder
      )
      return {
        backtests: (response.backtests as LightBacktestResponse[]) || [],
        totalCount: response.totalCount || 0,
        totalPages: response.totalPages || 0
      }
    },
    staleTime: 30000, // Consider data fresh for 30 seconds
    gcTime: 5 * 60 * 1000, // Keep in cache for 5 minutes (formerly cacheTime)
  })

  const backtests = backtestData?.backtests || []
  const totalBacktests = backtestData?.totalCount || 0
  const totalPages = backtestData?.totalPages || 0

  // Note: We no longer need to sync with the store since we're using TanStack Query
  // The store is kept for backward compatibility with other components

  // Handle errors
  useEffect(() => {
    if (error) {
      new Toast('Failed to load backtests', false)
    }
  }, [error])

  useEffect(() => {
    if (backtests && showModalRemoveBacktest) {
      calculateFilteredCount()
    }
  }, [backtests, showModalRemoveBacktest])

  const openModalRemoveBacktests = () => {
    setShowModalRemoveBacktest(true)
    // Calculate initial filtered count
    calculateFilteredCount()
  }

  const calculateFilteredCount = (formData?: any) => {
    if (!backtests) {
      setFilteredCount(0)
      return
    }

    const filters = formData || filterValues

    const filteredBacktests = backtests.filter((backtest: LightBacktestResponse) => {
      // Ensure values are numbers and handle potential null/undefined values
      const backtestWinRate = Number(backtest.winRate) || 0
      const backtestScore = Number(backtest.score) || 0
      
      // Debug logging to check the data structure
      console.log('Backtest:', {
        id: backtest.id,
        winRate: backtest.winRate,
        winRateNumber: backtestWinRate,
        score: backtest.score,
        scoreNumber: backtestScore,
        filters: filters
      })
      
      return (
        backtestWinRate <= filters.winRate &&
        backtestScore <= filters.score
      )
    })

    console.log('Filtered count:', filteredBacktests.length, 'Total:', backtests.length)
    setFilteredCount(filteredBacktests.length)
  }

  const updateFilterValue = (field: string, value: number) => {
    const newValues = { ...filterValues, [field]: value }
    setFilterValues(newValues)
    calculateFilteredCount(newValues)
  }

  const closeModalRemoveBacktest = () => {
    setShowModalRemoveBacktest(false)
  }

  const onSubmitRemoveBacktest = async (event: any) => {
    event.preventDefault()

    const form = {
      winRate: filterValues.winRate,
      score: filterValues.score,
    }
    
    const notify = new Toast(`Deleting Backtests...`)
    closeModalRemoveBacktest()

    if (!backtests) {
      return
    }

    const backTestToDelete = backtests.filter((backtest: LightBacktestResponse) => {
      // Ensure values are numbers and handle potential null/undefined values
      const backtestWinRate = Number(backtest.winRate) || 0
      const backtestScore = Number(backtest.score) || 0
      
      return (
        backtestWinRate <= form.winRate &&
        backtestScore <= form.score
      )
    })

    if (backTestToDelete.length === 0) {
      notify.update('warning', 'No backtests match the criteria')
      return
    }

    try {
      const backtestIds = backTestToDelete.map((backtest: any) => backtest.id)
      await backtestClient.backtest_DeleteBacktests({ backtestIds })
      notify.update('success', `${backTestToDelete.length} backtests deleted successfully`)
      
      // Invalidate and refetch backtests to update the list
      queryClient.invalidateQueries({ queryKey: ['backtests'] })
    } catch (err: any) {
      notify.update('error', err?.message || 'An error occurred while deleting backtests')
    }
  }

  function openModal() {
    setShowModal(true)
  }

  const closeModal = () => {
    setShowModal(false)
  }

  // Sorting handler
  const handleSortChange = (sortBy: string, sortOrder: 'asc' | 'desc') => {
    setCurrentSort({ sortBy, sortOrder })
    setCurrentPage(1)
  }

  // Pagination handler
  const handlePageChange = (newPage: number) => {
    if (newPage < 1 || (totalPages && newPage > totalPages)) return
    setCurrentPage(newPage)
  }

  if (isLoading) {
    return <Loader />
  }

  return (
    <div className="container mx-auto">
      <div className="tooltip" data-tip="Run backtest">
        <button className="btn btn-secondary m-1 text-xs" onClick={openModal}>
          <ColorSwatchIcon width="20"></ColorSwatchIcon>
        </button>
      </div>
      <div className="tooltip" data-tip="Delete all Backtests inferior to 50%">
        <button
          className="btn btn-primary m-1 text-xs"
          onClick={openModalRemoveBacktests}
        >
          <TrashIcon width="20"></TrashIcon>
        </button>
      </div>

      <BacktestTable
        list={backtests as LightBacktestResponse[]} // Cast to any for backward compatibility
        isFetching={isLoading}
        onSortChange={handleSortChange}
        currentSort={currentSort}
        onBacktestDeleted={() => {
          // Invalidate backtest queries when a backtest is deleted
          queryClient.invalidateQueries({ queryKey: ['backtests'] })
        }}
      />
      {/* Pagination controls */}
      {totalPages > 1 && (
        <div className="flex items-center gap-2 my-4">
          <button className="btn btn-sm" onClick={() => handlePageChange(currentPage - 1)} disabled={currentPage <= 1}>
            «
          </button>
          <span className="text-sm">Page {currentPage} of {totalPages}</span>
          <button className="btn btn-sm" onClick={() => handlePageChange(currentPage + 1)} disabled={currentPage >= totalPages}>
            »
          </button>
        </div>
      )}

      <UnifiedTradingModal
        mode="backtest"
        showModal={showModal}
        closeModal={closeModal}
        onBacktestComplete={() => {
          // Invalidate backtest queries when a new backtest is completed
          queryClient.invalidateQueries({ queryKey: ['backtests'] })
        }}
      />

      {/****************************/}
      {/* MODAL TO REMOVE BACKTEST */}
      {/****************************/}
      <Modal
        showModal={showModalRemoveBacktest}
        onSubmit={onSubmitRemoveBacktest}
        onClose={closeModalRemoveBacktest}
        titleHeader={'Delete Backtests by Filters'}
      >
        <div className="form-control">
          <div className="input-group">
            <label htmlFor="winRate" className="label mr-6">
              WinRate ≤
            </label>
            <div className="flex items-center gap-2">
              <input
                type="number"
                className="input input-sm w-20"
                name="winRate"
                value={filterValues.winRate}
                min="0"
                max="100"
                onChange={(e) => updateFilterValue('winRate', Number(e.target.value))}
              />
              <Slider
                id="winRate-slider"
                value={filterValues.winRate}
                onChange={(e: React.ChangeEvent<HTMLInputElement>) => updateFilterValue('winRate', Number(e.target.value))}
                min={0}
                max={100}
                step={1}
                prefixValue=""
                suffixValue="%"
              />
            </div>
          </div>
        </div>

        <div className="form-control">
          <div className="input-group">
            <label htmlFor="score" className="label mr-6">
              Score ≤
            </label>
            <div className="flex items-center gap-2">
              <input
                type="number"
                className="input input-sm w-20"
                name="score"
                value={filterValues.score}
                min="0"
                max={100}
                onChange={(e) => updateFilterValue('score', Number(e.target.value))}
              />
              <Slider
                id="score-slider"
                value={filterValues.score}
                onChange={(e: React.ChangeEvent<HTMLInputElement>) => updateFilterValue('score', Number(e.target.value))}
                min={0}
                max={100}
                step={1}
                prefixValue=""
                suffixValue=""
              />
            </div>
          </div>
        </div>
        <div className="alert alert-info mb-4">
          <div>
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" className="stroke-current shrink-0 w-6 h-6">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
            </svg>
            <span>This will delete {filteredCount} backtest{filteredCount !== 1 ? 's' : ''} that match the criteria</span>
          </div>
        </div>
        <div className="modal-action">
          <button type="submit" className="btn btn-error" disabled={filteredCount === 0}>
            Delete {filteredCount} Backtest{filteredCount !== 1 ? 's' : ''}
          </button>
        </div>
      </Modal>
    </div>
  )
}

export default BacktestScanner
