import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { Layout } from '@/components/layout/Layout'
import { BetList } from '@/components/bets/BetList'
import { CreateBetModal } from '@/components/bets/CreateBetModal'
import { Button } from '@/components/common/Button'
import { Loading } from '@/components/common/Loading'
import { betsApi } from '@/api/bets'
import { Plus } from 'lucide-react'
import type { BetCategory } from '@/types'
import { BET_CATEGORIES } from '@/utils/constants'

export const BetMarketplace = () => {
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false)
  const [selectedCategory, setSelectedCategory] = useState<BetCategory | undefined>()

  const { data: bets, isLoading } = useQuery({
    queryKey: ['bets', selectedCategory],
    queryFn: () => betsApi.getBets({ category: selectedCategory }),
  })

  return (
    <Layout>
      <div className="space-y-6">
        <div className="flex justify-between items-center">
          <div>
            <h1 className="text-3xl font-bold text-gray-900">Bet Marketplace</h1>
            <p className="text-gray-600 mt-2">Browse and accept open bets from other users</p>
          </div>
          <Button onClick={() => setIsCreateModalOpen(true)}>
            <Plus size={20} className="mr-2" />
            Create Bet
          </Button>
        </div>

        <div className="flex gap-2 flex-wrap">
          <button
            onClick={() => setSelectedCategory(undefined)}
            className={`px-4 py-2 rounded-lg transition-colors ${
              selectedCategory === undefined
                ? 'bg-primary text-white'
                : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
            }`}
          >
            All
          </button>
          {Object.entries(BET_CATEGORIES).map(([value, label]) => (
            <button
              key={value}
              onClick={() => setSelectedCategory(value as BetCategory)}
              className={`px-4 py-2 rounded-lg transition-colors ${
                selectedCategory === value
                  ? 'bg-primary text-white'
                  : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
              }`}
            >
              {label}
            </button>
          ))}
        </div>

        {isLoading ? (
          <Loading />
        ) : bets ? (
          <BetList bets={bets} />
        ) : null}
      </div>

      <CreateBetModal
        isOpen={isCreateModalOpen}
        onClose={() => setIsCreateModalOpen(false)}
      />
    </Layout>
  )
}
