import { useZocksStore } from '../../app'
import {
  clearAIFeatures,
  initAIFeatures,
  initAIResults,
  selectAIFeatures,
  selectAIFeaturesStatus,
  setAIFeaturesError,
  setAIFeaturesStatus,
} from './aiFeatureSlice'
import { useZocksDispatch } from '../../app/hooks'
import { useCallback, useEffect } from 'react'
import { ZocksAIActions } from '../session'
import { AIFeaturesStatus } from './models'

export const useAIFeatures = (aiActions: ZocksAIActions) => {
  const dispatch = useZocksDispatch()
  const { listAIFeatures, listAIResults } = aiActions

  const aiFeatures = useZocksStore(selectAIFeatures)
  const aiFeaturesStatus = useZocksStore(selectAIFeaturesStatus)

  const loadAIFeaturesWithResults = useCallback(async () => {
    dispatch(setAIFeaturesStatus(AIFeaturesStatus.LOADING))
    try {
      const result = await listAIFeatures()
      dispatch(initAIFeatures(result))
      dispatch(setAIFeaturesStatus(AIFeaturesStatus.LOADING))
      const aiResults = await listAIResults()
      dispatch(initAIResults(aiResults))
    } catch (error: any) {
      dispatch(setAIFeaturesError(error))
    }
  }, [dispatch, listAIFeatures, listAIResults])

  useEffect(() => {
    if (aiFeaturesStatus === AIFeaturesStatus.INITIAL) {
      loadAIFeaturesWithResults().catch(console.error)
    }
  }, [dispatch, loadAIFeaturesWithResults, aiFeaturesStatus])

  const resetAIFeatures = () => {
    dispatch(clearAIFeatures())
  }

  return { aiFeatures, aiFeaturesStatus, resetAIFeatures, loadAIFeaturesWithResults }
}
