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

export default function LeaderboardWidget() {
  const [searchParams] = useSearchParams()
  const [data, setData] = useState<WidgetLeaderboardData | 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 count = parseInt(searchParams.get('count') || '5')
  const showAvatars = searchParams.get('avatars') !== 'false'
  const transparent = searchParams.get('transparent') === 'true'

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

    const fetchData = async () => {
      try {
        const result = await widgetsApi.getLeaderboard(parseInt(marathonId), token, count)
        setData(result)
        setError(null)
      } catch {
        setError('Failed to load data')
      }
    }

    fetchData()
    const interval = setInterval(fetchData, 30000) // Refresh every 30 seconds
    return () => clearInterval(interval)
  }, [marathonId, token, count])

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

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

  return (
    <div className={`widget widget-theme-${theme} ${transparent ? 'widget-transparent' : ''}`}>
      <div className="widget-leaderboard">
        <h3 className="widget-title">{data.marathon_title}</h3>
        <div className="widget-leaderboard-list">
          {data.entries.map((entry) => (
            <div
              key={entry.rank}
              className={`widget-leaderboard-row ${entry.is_current_user ? 'widget-highlight' : ''}`}
            >
              <span className="widget-rank">#{entry.rank}</span>
              {showAvatars && (
                <div className="widget-avatar">
                  {entry.avatar_url ? (
                    <img src={entry.avatar_url} alt="" />
                  ) : (
                    <div className="widget-avatar-placeholder">
                      {entry.nickname.charAt(0).toUpperCase()}
                    </div>
                  )}
                </div>
              )}
              <span className="widget-nickname">{entry.nickname}</span>
              <span className="widget-points">{entry.total_points} pts</span>
              {entry.current_streak > 0 && (
                <span className="widget-streak">
                  <Flame className="w-3 h-3 text-orange-400 inline" />
                  {entry.current_streak}
                </span>
              )}
            </div>
          ))}
        </div>
        {data.current_user_rank && data.current_user_rank > count && (
          <div className="widget-current-rank">
            Ваше место: #{data.current_user_rank}
          </div>
        )}
      </div>
    </div>
  )
}
