import React, { useState, useEffect } from 'react'
import DatasetSelector from './DatasetSelector'
import LeaderboardTable from './LeaderboardTable'
import LeaderboardChart from './LeaderboardChart'
import ModelFilter from './ModelFilter'
import API from '../API'
import LoadingSpinner from './LoadingSpinner'

interface LeaderboardPageProps {
  datasetType: 'audio' | 'image' | 'video'
}

const LeaderboardPage: React.FC<LeaderboardPageProps> = ({ datasetType }) => {
  // State for dataset names fetched from backend
  const [datasetNames, setDatasetNames] = useState<string[]>([])
  const [selectedDatasetName, setSelectedDatasetName] = useState<string>('')
  const [models, setModels] = useState<string[]>([])
  const [selectedModels, setSelectedModels] = useState<Set<string>>(new Set())
  const [loading, setLoading] = useState(true)
  const [benchmarkData, setBenchmarkData] = useState<any>(null)

  // Fetch dataset names from backend on mount or when datasetType changes
  useEffect(() => {
    setLoading(true)
    API.fetchDatasets()
      .then((grouped) => {
        const filtered = grouped[datasetType] || []
        setDatasetNames(filtered)
        setSelectedDatasetName(filtered[0] || '')
        setLoading(false)
      })
      .catch((err) => {
        console.error('Failed to fetch dataset names:', err)
        setDatasetNames([])
        setSelectedDatasetName('')
        setLoading(false)
      })
  }, [datasetType])

  // Fetch available models when dataset changes
  useEffect(() => {
    if (!selectedDatasetName) return
    setLoading(true)
    API.fetchStaticFile(`data/${selectedDatasetName}?dataset_type=benchmark`)
      .then((response) => {
        const data = JSON.parse(response)
        const rows = data['rows']
        const allKeys: string[] = Array.from(new Set(rows.flatMap((row: any) => Object.keys(row))))
        // Remove 'metric' from headers if it exists
        const headers = allKeys.filter((key) => key !== 'metric')
        setModels(headers)
        setSelectedModels(new Set(headers))
        setBenchmarkData(data)
        setLoading(false)
      })
      .catch((err) => {
        console.error('Failed to fetch models:', err)
        setLoading(false)
      })
  }, [selectedDatasetName])

  return (
    <div className="">
      {loading ? (
        <LoadingSpinner />
      ) : (
        <>
          <div className="flex flex-col gap-4">
            <DatasetSelector
              datasetNames={datasetNames}
              selectedDatasetName={selectedDatasetName}
              onDatasetNameChange={setSelectedDatasetName}
            />
          </div>
          {models.length > 0 && (
            <ModelFilter
              models={models}
              selectedModels={selectedModels}
              setSelectedModels={setSelectedModels}
            />
          )}
          <div className="space-y-8">
            <LeaderboardTable benchmarkData={benchmarkData} selectedModels={selectedModels} />
            <div className="mt-8 pt-4 border-t border-gray-200">
              <LeaderboardChart
                datasetType={datasetType}
                dataset={selectedDatasetName}
                selectedModels={selectedModels}
              />
            </div>
          </div>
        </>
      )}
    </div>
  )
}

export default LeaderboardPage
