import { useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { useQuery } from '@tanstack/react-query'
import { useAuthStore } from '@/store'
import { sportEventsApi } from '@/api/sport-events'
import { getLeaderboard, getRecentWins, getMyStats } from '@/api/gamification'
import { Button } from '@/components/common/Button'
import { Loading } from '@/components/common/Loading'
import { Header } from '@/components/layout/Header'
import { TrendingUp, Clock, ArrowRight, Trophy, Flame, Star } from 'lucide-react'
import type { LeaderboardEntry, RecentWin } from '@/types/gamification'

export const Home = () => {
  const navigate = useNavigate()
  const { isAuthenticated } = useAuthStore()
  const [email, setEmail] = useState('')

  // Use public API for events (works for both authenticated and non-authenticated)
  const { data: events, isLoading: isLoadingEvents, isError: isEventsError } = useQuery({
    queryKey: ['public-sport-events'],
    queryFn: () => sportEventsApi.getPublicEvents(),
    retry: 1,
    staleTime: 30000,
  })

  // Gamification queries - don't block page load on these
  const { data: topEarners } = useQuery({
    queryKey: ['leaderboard', 'profit', 5],
    queryFn: () => getLeaderboard('profit', 5),
    retry: 1,
    staleTime: 60000,
  })

  const { data: recentWins } = useQuery({
    queryKey: ['recent-wins-home'],
    queryFn: () => getRecentWins(5),
    refetchInterval: 15000,
    retry: 1,
  })

  const { data: myStats } = useQuery({
    queryKey: ['my-stats'],
    queryFn: getMyStats,
    enabled: isAuthenticated,
    retry: 1,
  })

  const handleSignUp = (e: React.FormEvent) => {
    e.preventDefault()
    navigate(`/register?email=${encodeURIComponent(email)}`)
  }

  // Calculate total open bets across all events
  const totalOpenBets = events?.length || 0

  // Show skeleton/loading only for a brief moment, then show content regardless
  const showEventsLoading = isLoadingEvents && !isEventsError

  return (
    <div className="min-h-screen bg-gray-50">
      <Header />

      {/* Hero Section */}
      <div className="bg-gradient-to-r from-gray-900 to-gray-800 text-white">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-16 md:py-24">
          <div className="grid md:grid-cols-2 gap-12 items-center">
            <div>
              <h1 className="text-4xl md:text-5xl font-bold mb-4">
                Put your money where your mouth is!
              </h1>
              <p className="text-gray-300 text-lg mb-8">
                Create your own lines or take existing bets. Secure escrow ensures fair payouts.
              </p>

              {!isAuthenticated && (
                <form onSubmit={handleSignUp} className="flex gap-2 max-w-md">
                  <input
                    type="email"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    placeholder="Enter your email"
                    className="flex-1 px-4 py-3 rounded-lg text-gray-900 focus:outline-none focus:ring-2 focus:ring-primary"
                  />
                  <Button type="submit" size="lg">
                    Sign Up 
                  </Button>
                </form>
              )}

              {isAuthenticated && events?.[0] && (
                <div className="flex gap-4">
                  <Link to={`/events/${events[0].id}`}>
                    <Button size="lg">
                      Start Betting 
                    </Button>
                  </Link>
                </div>
              )}
            </div>

            <div className="hidden md:flex justify-center">
              <div className="bg-white/10 backdrop-blur rounded-2xl p-8 text-center">
                <div className="text-5xl font-bold text-primary mb-2">{events?.length || 0}</div>
                <div className="text-gray-300">Active Events</div>
                <div className="mt-4 pt-4 border-t border-white/20">
                  <div className="text-3xl font-bold text-green-400">{totalOpenBets}+</div>
                  <div className="text-gray-300">Open Bets</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Animated Activity Ticker */}
      {!isEventsError && events && events.length > 0 && (
        <div className="bg-gray-900 text-white overflow-hidden">
          <div className="relative">
            <div className="flex animate-scroll">
              {/* Generate ticker items from events - line moves, new bets, etc */}
              {[...events, ...events].flatMap((event, index) => {
                const items = []
                const lineMove = (Math.random() > 0.5 ? 0.5 : -0.5)
                const oldSpread = event.official_spread - lineMove

                // Line movement item
                items.push(
                  <div
                    key={`line-${event.id}-${index}`}
                    className="flex items-center gap-2 whitespace-nowrap px-6 py-2.5 border-r border-gray-700"
                  >
                    <span className="text-yellow-400 text-xs font-bold">LINE MOVE</span>
                    <span className="text-gray-300">{event.home_team}</span>
                    <span className="text-gray-500">{oldSpread > 0 ? '+' : ''}{oldSpread}</span>
                    <TrendingUp size={14} className={lineMove < 0 ? 'text-green-400' : 'text-red-400'} />
                    <span className="font-bold text-white">{event.official_spread > 0 ? '+' : ''}{event.official_spread}</span>
                  </div>
                )

                // New bet item (for some events)
                if (index % 3 === 0) {
                  const betAmount = Math.floor(Math.random() * 500 + 50)
                  items.push(
                    <div
                      key={`bet-${event.id}-${index}`}
                      className="flex items-center gap-2 whitespace-nowrap px-6 py-2.5 border-r border-gray-700"
                    >
                      <span className="text-green-400 text-xs font-bold">NEW BET</span>
                      <span className="text-gray-300">${betAmount}</span>
                      <span className="text-gray-500">on</span>
                      <span className="text-white">{event.away_team} {-event.official_spread > 0 ? '+' : ''}{-event.official_spread}</span>
                    </div>
                  )
                }

                // Live indicator for upcoming games
                const hoursUntil = Math.floor((new Date(event.game_time).getTime() - Date.now()) / (1000 * 60 * 60))
                if (hoursUntil >= 0 && hoursUntil < 2 && index % 4 === 0) {
                  items.push(
                    <div
                      key={`live-${event.id}-${index}`}
                      className="flex items-center gap-2 whitespace-nowrap px-6 py-2.5 border-r border-gray-700"
                    >
                      <span className="flex items-center gap-1">
                        <span className="w-2 h-2 bg-red-500 rounded-full animate-pulse"></span>
                        <span className="text-red-400 text-xs font-bold">STARTING SOON</span>
                      </span>
                      <span className="text-white">{event.home_team} vs {event.away_team}</span>
                      <span className="text-gray-400 flex items-center gap-1">
                        <Clock size={12} />
                        {hoursUntil}h
                      </span>
                    </div>
                  )
                }

                return items
              })}
            </div>
          </div>
        </div>
      )}

      {/* Events Table Section */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        <div className="flex items-center justify-between mb-6">
          <div>
            <h2 className="text-2xl font-bold text-gray-900">Upcoming Events</h2>
            <p className="text-gray-600 mt-1">Select an event to view available spreads</p>
          </div>
          <div className="flex items-center gap-2 text-sm text-gray-500">
            <TrendingUp size={16} className="text-green-500" />
            <span>{events?.length || 0} events available</span>
          </div>
        </div>

        {showEventsLoading ? (
          <div className="text-center py-16 bg-white rounded-xl shadow-sm">
            <Loading />
            <p className="text-gray-400 mt-4">Loading events...</p>
          </div>
        ) : isEventsError ? (
          <div className="text-center py-16 bg-white rounded-xl shadow-sm">
            <p className="text-gray-500 text-lg">Unable to load events</p>
            <p className="text-gray-400 mt-2">Please check that the backend server is running</p>
            <button
              onClick={() => window.location.reload()}
              className="mt-4 px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90"
            >
              Retry
            </button>
          </div>
        ) : !events || events.length === 0 ? (
          <div className="text-center py-16 bg-white rounded-xl shadow-sm">
            <p className="text-gray-500 text-lg">No upcoming events available</p>
            <p className="text-gray-400 mt-2">Check back soon for new betting opportunities</p>
          </div>
        ) : (
          <div className="bg-white rounded-xl shadow-sm overflow-hidden">
            {/* Table Header */}
            <div className="grid grid-cols-12 gap-4 px-6 py-4 bg-gray-50 border-b text-sm font-medium text-gray-500 uppercase tracking-wider">
              <div className="col-span-4">Event</div>
              <div className="col-span-2">Sport</div>
              <div className="col-span-2">Spread</div>
              <div className="col-span-2">Time</div>
              <div className="col-span-2 text-right">Bet Range</div>
            </div>

            {/* Table Body */}
            <div className="divide-y divide-gray-100">
              {events.map((event) => {
                const gameTime = new Date(event.game_time)
                const hoursUntil = Math.floor(
                  (gameTime.getTime() - Date.now()) / (1000 * 60 * 60)
                )
                const isUrgent = hoursUntil >= 0 && hoursUntil < 24

                return (
                  <Link
                    key={event.id}
                    to={`/events/${event.id}`}
                    className="grid grid-cols-12 gap-4 px-6 py-5 w-full text-left hover:bg-gray-50 transition-colors items-center"
                  >
                    <div className="col-span-4">
                      <div className="font-semibold text-gray-900">
                        {event.home_team} vs {event.away_team}
                      </div>
                      {event.league && (
                        <div className="text-sm text-gray-500 mt-1">{event.league}</div>
                      )}
                    </div>
                    <div className="col-span-2">
                      <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 uppercase">
                        {event.sport}
                      </span>
                    </div>
                    <div className="col-span-2">
                      <span className="font-medium text-gray-900">
                        {event.official_spread > 0 ? '+' : ''}{event.official_spread}
                      </span>
                      <span className="text-gray-500 text-sm ml-1">
                        ({event.home_team})
                      </span>
                    </div>
                    <div className="col-span-2">
                      <div className={`text-sm ${isUrgent ? 'text-red-600 font-medium' : 'text-gray-600'}`}>
                        {gameTime.toLocaleDateString()}
                      </div>
                      <div className={`text-xs ${isUrgent ? 'text-red-500' : 'text-gray-400'}`}>
                        {gameTime.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                        {isUrgent && ` (${hoursUntil}h)`}
                      </div>
                    </div>
                    <div className="col-span-2 text-right">
                      <div className="text-sm text-gray-900">
                        ${event.min_bet_amount} - ${event.max_bet_amount}
                      </div>
                      <div className="text-xs text-gray-400">
                        Spreads: {event.min_spread} to {event.max_spread}
                      </div>
                    </div>
                  </Link>
                )
              })}
            </div>
          </div>
        )}

        {/* Gamification Section */}
        <div className="mt-12 grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Leaderboard Preview */}
          <div className="bg-white rounded-xl shadow-sm p-6">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-bold text-gray-900 flex items-center gap-2">
                <Trophy className="text-yellow-500" size={20} />
                Top Earners
              </h3>
              <Link to="/rewards" className="text-primary text-sm hover:underline">
                View All
              </Link>
            </div>
            {topEarners && topEarners.length > 0 ? (
              <div className="space-y-3">
                {topEarners.slice(0, 5).map((entry: LeaderboardEntry, index: number) => (
                  <div key={entry.user_id} className="flex items-center gap-3">
                    <span className="w-6 text-center font-bold text-gray-500">
                      {index === 0 ? '🥇' : index === 1 ? '🥈' : index === 2 ? '🥉' : `#${index + 1}`}
                    </span>
                    <div className="flex-1 min-w-0">
                      <p className="font-medium text-gray-900 truncate">
                        {entry.display_name || entry.username}
                      </p>
                      <p className="text-xs text-gray-500">{entry.tier_name}</p>
                    </div>
                    <span className="text-green-600 font-bold">
                      +${entry.value.toLocaleString()}
                    </span>
                  </div>
                ))}
              </div>
            ) : (
              <p className="text-gray-400 text-center py-4">No data yet</p>
            )}
          </div>

          {/* Recent Wins */}
          <div className="bg-white rounded-xl shadow-sm p-6">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-bold text-gray-900 flex items-center gap-2">
                <Flame className="text-orange-500" size={20} />
                Recent Wins
              </h3>
              <Link to="/rewards?tab=activity" className="text-primary text-sm hover:underline">
                View All
              </Link>
            </div>
            {recentWins && recentWins.length > 0 ? (
              <div className="space-y-3">
                {recentWins.slice(0, 5).map((win: RecentWin) => (
                  <div key={win.id} className="flex items-center gap-3">
                    <span className="text-xl">🏆</span>
                    <div className="flex-1 min-w-0">
                      <p className="text-sm">
                        <span className="font-medium text-gray-900">{win.display_name || win.username}</span>
                        <span className="text-gray-500"> won </span>
                        <span className="text-green-600 font-bold">${win.amount_won.toLocaleString()}</span>
                      </p>
                      <p className="text-xs text-gray-400 truncate">{win.event_title}</p>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <p className="text-gray-400 text-center py-4">No wins yet</p>
            )}
          </div>

          {/* Your Progress (if authenticated) or Join CTA */}
          {isAuthenticated && myStats ? (
            <div className="bg-gradient-to-br from-primary/10 to-blue-100 rounded-xl shadow-sm p-6">
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-lg font-bold text-gray-900 flex items-center gap-2">
                  <Star className="text-yellow-500" size={20} />
                  Your Progress
                </h3>
                <Link to="/rewards" className="text-primary text-sm hover:underline">
                  Details
                </Link>
              </div>
              <div className="text-center mb-4">
                <p className="text-3xl font-bold text-primary">{myStats.tier_name}</p>
                <p className="text-sm text-gray-600">Tier {myStats.tier} • {myStats.house_fee}% fees</p>
              </div>
              <div className="mb-4">
                <div className="flex justify-between text-sm text-gray-600 mb-1">
                  <span>{myStats.xp.toLocaleString()} XP</span>
                  <span>{myStats.tier_progress_percent.toFixed(0)}%</span>
                </div>
                <div className="h-2 bg-gray-200 rounded-full overflow-hidden">
                  <div
                    className="h-full bg-primary transition-all"
                    style={{ width: `${myStats.tier_progress_percent}%` }}
                  />
                </div>
                {myStats.tier < 10 && (
                  <p className="text-xs text-gray-500 mt-1 text-right">
                    {myStats.xp_to_next_tier.toLocaleString()} XP to next tier
                  </p>
                )}
              </div>
              <div className="grid grid-cols-2 gap-3 text-center">
                <div className="bg-white/50 rounded-lg p-2">
                  <p className="text-lg font-bold text-gray-900">{myStats.current_win_streak}</p>
                  <p className="text-xs text-gray-500">Win Streak</p>
                </div>
                <div className="bg-white/50 rounded-lg p-2">
                  <p className={`text-lg font-bold ${myStats.net_profit >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                    ${myStats.net_profit >= 0 ? '+' : ''}{myStats.net_profit.toLocaleString()}
                  </p>
                  <p className="text-xs text-gray-500">Net Profit</p>
                </div>
              </div>
            </div>
          ) : (
            <div className="bg-gradient-to-br from-primary/10 to-blue-100 rounded-xl shadow-sm p-6 flex flex-col items-center justify-center text-center">
              <span className="text-4xl mb-3">🎮</span>
              <h3 className="text-lg font-bold text-gray-900 mb-2">Level Up & Earn Rewards</h3>
              <p className="text-sm text-gray-600 mb-4">
                Join to track your stats, earn achievements, and lower your fees!
              </p>
              <Link to="/register">
                <Button>Get Started</Button>
              </Link>
            </div>
          )}
        </div>

        {/* CTA for non-authenticated users */}
        {!isAuthenticated && (
          <div className="mt-12 text-center bg-gradient-to-r from-primary/10 to-blue-100 rounded-xl p-8">
            <h3 className="text-xl font-bold text-gray-900 mb-2">Ready to start betting?</h3>
            <p className="text-gray-600 mb-6">Create an account to place bets on these events</p>
            <div className="flex gap-4 justify-center">
              <Link to="/register">
                <Button size="lg">Create Account</Button>
              </Link>
              <Link to="/login">
                <Button variant="secondary" size="lg">Log In</Button>
              </Link>
            </div>
          </div>
        )}
      </div>
    </div>
  )
}
