import { useQuery } from '@tanstack/react-query'
import { getActivityFeed, getRecentWins } from '../../api/gamification'
import { formatDistanceToNow } from 'date-fns'
import type { ActivityFeedItem, RecentWin } from '../../types/gamification'

const ACTIVITY_ICONS: Record<string, string> = {
  bet_placed: '🎲',
  bet_won: '🏆',
  bet_lost: '😢',
  achievement: '🎖️',
  tier_up: '⬆️',
  whale_bet: '🐋',
  loot_box: '🎁',
  daily_reward: '📅',
}

interface ActivityFeedProps {
  showRecentWins?: boolean
  limit?: number
}

export default function ActivityFeed({ showRecentWins = true, limit = 15 }: ActivityFeedProps) {
  const { data: activities = [], isLoading: loadingActivities } = useQuery({
    queryKey: ['activity-feed', limit],
    queryFn: () => getActivityFeed(limit),
    refetchInterval: 10000,
    retry: 1,
  })

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

  return (
    <div className="space-y-6">
      {/* Recent Wins Section */}
      {showRecentWins && (
        <div className="bg-white rounded-xl shadow-sm p-6">
          <h3 className="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2">
            <span className="text-2xl">🏆</span> Recent Wins
          </h3>

          {loadingWins ? (
            <div className="space-y-2">
              {[...Array(3)].map((_, i) => (
                <div key={i} className="h-12 bg-gray-100 rounded-lg animate-pulse" />
              ))}
            </div>
          ) : recentWins.length === 0 ? (
            <p className="text-gray-500 text-center py-3">No recent wins</p>
          ) : (
            <div className="space-y-2">
              {recentWins.map((win: RecentWin) => (
                <div
                  key={win.id}
                  className="flex items-center gap-3 bg-gradient-to-r from-green-50 to-transparent p-2 rounded-lg border border-green-100"
                >
                  <div className="w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center overflow-hidden flex-shrink-0">
                    {win.avatar_url ? (
                      <img src={win.avatar_url} alt="" className="w-full h-full object-cover" />
                    ) : (
                      <span className="text-sm font-medium text-gray-600">{win.username[0].toUpperCase()}</span>
                    )}
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-gray-900 text-sm truncate">
                      <span className="font-medium">{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-500 truncate">{win.event_title}</p>
                  </div>
                  <span className="text-xs text-gray-400 flex-shrink-0">
                    {formatDistanceToNow(new Date(win.settled_at), { addSuffix: true })}
                  </span>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* Activity Feed */}
      <div className="bg-white rounded-xl shadow-sm p-6">
        <h3 className="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2">
          <span className="text-2xl">📢</span> Live Activity
        </h3>

        {loadingActivities ? (
          <div className="space-y-2">
            {[...Array(5)].map((_, i) => (
              <div key={i} className="h-10 bg-gray-100 rounded-lg animate-pulse" />
            ))}
          </div>
        ) : activities.length === 0 ? (
          <p className="text-gray-500 text-center py-4">No activity yet</p>
        ) : (
          <div className="space-y-1 max-h-80 overflow-y-auto">
            {activities.map((activity: ActivityFeedItem) => (
              <div
                key={activity.id}
                className="flex items-start gap-2 py-2 border-b border-gray-100 last:border-0"
              >
                <span className="text-lg flex-shrink-0">
                  {ACTIVITY_ICONS[activity.activity_type] || '📌'}
                </span>
                <div className="flex-1 min-w-0">
                  <p className="text-sm text-gray-600">
                    <span className="text-gray-900 font-medium">{activity.username}</span>{' '}
                    {activity.message}
                    {activity.amount && (
                      <span className="text-green-600 font-medium ml-1">
                        ${activity.amount.toLocaleString()}
                      </span>
                    )}
                  </p>
                  <p className="text-xs text-gray-400">
                    {formatDistanceToNow(new Date(activity.created_at), { addSuffix: true })}
                  </p>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}
