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

export default function ProgressWidget() {
  const [searchParams] = useSearchParams()
  const [data, setData] = 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 result = await widgetsApi.getProgress(parseInt(marathonId), token)
        setData(result)
        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 (!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-progress">
        <div className="widget-progress-header">
          {showAvatars && (
            <div className="widget-avatar widget-avatar-lg">
              {data.avatar_url ? (
                <img src={data.avatar_url} alt="" />
              ) : (
                <div className="widget-avatar-placeholder">
                  {data.nickname.charAt(0).toUpperCase()}
                </div>
              )}
            </div>
          )}
          <div className="widget-progress-user">
            <div className="widget-nickname-lg">{data.nickname}</div>
            <div className="widget-marathon-title">{data.marathon_title}</div>
          </div>
        </div>

        <div className="widget-progress-stats">
          <div className="widget-stat">
            <span className="widget-stat-value">#{data.rank}</span>
            <span className="widget-stat-label">Место</span>
          </div>
          <div className="widget-stat">
            <span className="widget-stat-value">{data.total_points}</span>
            <span className="widget-stat-label">Очки</span>
          </div>
          <div className="widget-stat">
            <span className="widget-stat-value">
              <Flame className="w-5 h-5 text-orange-400 inline" />
              {data.current_streak}
            </span>
            <span className="widget-stat-label">Стрик</span>
          </div>
        </div>

        <div className="widget-progress-counts">
          <span className="widget-completed">✓ {data.completed_count}</span>
          <span className="widget-dropped">✗ {data.dropped_count}</span>
        </div>
      </div>
    </div>
  )
}
