import { useEffect, useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import { Flame, Trophy, Target, TrendingDown, CheckCircle } from 'lucide-react'
import { widgetsApi } from '@/api/widgets'
import type { WidgetLeaderboardData, WidgetCurrentData, WidgetProgressData } from '@/types'
import '@/styles/widget.css'

export default function CombinedWidget() {
  const [searchParams] = useSearchParams()
  const [leaderboard, setLeaderboard] = useState<WidgetLeaderboardData | null>(null)
  const [current, setCurrent] = useState<WidgetCurrentData | null>(null)
  const [progress, setProgress] = useState<WidgetProgressData | null>(null)
  const [error, setError] = useState<string | null>(null)

  const marathonId = searchParams.get('marathon')
  const token = searchParams.get('token')
  const theme = searchParams.get('theme') || 'dark'
  const transparent = searchParams.get('transparent') === 'true'
  const showAvatars = searchParams.get('avatars') !== 'false'

  useEffect(() => {
    if (!marathonId || !token) {
      setError('Missing marathon or token parameter')
      return
    }

    const fetchData = async () => {
      try {
        const [leaderboardData, currentData, progressData] = await Promise.all([
          widgetsApi.getLeaderboard(parseInt(marathonId), token, 3),
          widgetsApi.getCurrent(parseInt(marathonId), token),
          widgetsApi.getProgress(parseInt(marathonId), token),
        ])
        setLeaderboard(leaderboardData)
        setCurrent(currentData)
        setProgress(progressData)
        setError(null)
      } catch {
        setError('Failed to load data')
      }
    }

    fetchData()
    const interval = setInterval(fetchData, 30000)
    return () => clearInterval(interval)
  }, [marathonId, token])

  if (error) {
    return (
      <div className={`widget widget-theme-${theme} ${transparent ? 'widget-transparent' : ''}`}>
        <div className="widget-error">{error}</div>
      </div>
    )
  }

  if (!leaderboard || !current || !progress) {
    return (
      <div className={`widget widget-theme-${theme} ${transparent ? 'widget-transparent' : ''}`}>
        <div className="widget-loading">Loading...</div>
      </div>
    )
  }

  return (
    <div className={`widget widget-combined widget-theme-${theme} ${transparent ? 'widget-transparent' : ''}`}>
      {/* Header with user info */}
      <div className="widget-combined-header">
        {showAvatars && (
          <div className="widget-avatar">
            {progress.avatar_url ? (
              <img src={progress.avatar_url} alt="" />
            ) : (
              <div className="widget-avatar-placeholder">
                {progress.nickname.charAt(0).toUpperCase()}
              </div>
            )}
          </div>
        )}
        <div className="widget-combined-user">
          <div className="widget-nickname">{progress.nickname}</div>
          <div className="widget-combined-stats">
            <span className="widget-combined-stat">
              <Trophy className="w-3 h-3" />
              #{progress.rank}
            </span>
            <span className="widget-combined-stat">
              {progress.total_points} pts
            </span>
            {progress.current_streak > 0 && (
              <span className="widget-combined-stat widget-streak-highlight">
                <Flame className="w-3 h-3" />
                {progress.current_streak}
              </span>
            )}
          </div>
        </div>
      </div>

      {/* Current assignment */}
      {current.has_assignment && (
        <div className="widget-combined-current">
          <div className="widget-combined-current-header">
            <Target className="w-4 h-4 text-primary" />
            <span className="widget-combined-game">{current.game_title}</span>
          </div>
          <div className="widget-combined-challenge">
            {current.challenge_title}
            {current.points && (
              <span className="widget-combined-points">+{current.points}</span>
            )}
          </div>
          {current.bonus_total !== null && current.bonus_total > 0 && (
            <div className="widget-combined-bonus">
              Бонусы: {current.bonus_completed}/{current.bonus_total}
            </div>
          )}
        </div>
      )}

      {/* Mini leaderboard */}
      <div className="widget-combined-leaderboard">
        {leaderboard.entries.map((entry) => (
          <div
            key={entry.rank}
            className={`widget-combined-row ${entry.is_current_user ? 'widget-highlight' : ''}`}
          >
            <span className="widget-combined-rank">#{entry.rank}</span>
            {showAvatars && (
              <div className="widget-avatar widget-avatar-xs">
                {entry.avatar_url ? (
                  <img src={entry.avatar_url} alt="" />
                ) : (
                  <div className="widget-avatar-placeholder">
                    {entry.nickname.charAt(0).toUpperCase()}
                  </div>
                )}
              </div>
            )}
            <span className="widget-combined-name">{entry.nickname}</span>
            <span className="widget-combined-pts">{entry.total_points}</span>
          </div>
        ))}
      </div>

      {/* Footer stats */}
      <div className="widget-combined-footer">
        <span className="widget-completed">
          <CheckCircle className="w-3 h-3" />
          {progress.completed_count}
        </span>
        <span className="widget-dropped">
          <TrendingDown className="w-3 h-3" />
          {progress.dropped_count}
        </span>
      </div>
    </div>
  )
}
