import { useState, useEffect, useCallback, useRef, useImperativeHandle, forwardRef } from 'react'
import { useNavigate, Link } from 'react-router-dom'
import { feedApi } from '@/api'
import type { Activity, ActivityType, ShopItemPublic, User } from '@/types'
import { Loader2, ChevronDown, Activity as ActivityIcon, ExternalLink, AlertTriangle, Sparkles, Zap } from 'lucide-react'
import { UserAvatar } from '@/components/ui'
import {
  formatRelativeTime,
  getActivityIcon,
  getActivityColor,
  isEventActivity,
  formatActivityMessage,
} from '@/utils/activity'

// Helper to get name color styles and animation class
function getNameColorData(nameColor: ShopItemPublic | null | undefined): { styles: React.CSSProperties; className: string } {
  if (!nameColor?.asset_data) return { styles: {}, className: '' }

  const data = nameColor.asset_data as { style?: string; color?: string; gradient?: string[]; animation?: string }

  if (data.style === 'gradient' && data.gradient) {
    return {
      styles: {
        background: `linear-gradient(90deg, ${data.gradient.join(', ')})`,
        WebkitBackgroundClip: 'text',
        WebkitTextFillColor: 'transparent',
        backgroundClip: 'text',
      },
      className: '',
    }
  }

  if (data.style === 'animated') {
    return {
      styles: {
        background: 'linear-gradient(90deg, #ff0000, #ff7f00, #ffff00, #00ff00, #0000ff, #9400d3, #ff0000)',
        backgroundSize: '400% 100%',
        WebkitBackgroundClip: 'text',
        WebkitTextFillColor: 'transparent',
        backgroundClip: 'text',
      },
      className: 'animate-rainbow-rotate',
    }
  }

  if (data.style === 'solid' && data.color) {
    return { styles: { color: data.color }, className: '' }
  }

  return { styles: {}, className: '' }
}

// Helper to get title data
function getTitleData(title: ShopItemPublic | null | undefined): { text: string; color: string } | null {
  if (!title?.asset_data) return null

  const data = title.asset_data as { text?: string; color?: string }
  if (!data.text) return null

  return {
    text: data.text,
    color: data.color || '#ffffff',
  }
}

// Styled nickname component for activity feed
function StyledNickname({ user }: { user: User }) {
  const nameColorData = getNameColorData(user.equipped_name_color)
  const titleData = getTitleData(user.equipped_title)

  return (
    <>
      <span className={nameColorData.className} style={nameColorData.styles}>{user.nickname}</span>
      {titleData && (
        <span
          className="ml-1.5 px-1 py-0.5 text-[10px] font-medium rounded bg-dark-700/50"
          style={{ color: titleData.color }}
        >
          {titleData.text}
        </span>
      )}
    </>
  )
}

interface ActivityFeedProps {
  marathonId: number
  className?: string
}

export interface ActivityFeedRef {
  refresh: () => void
}

const ITEMS_PER_PAGE = 20
const POLL_INTERVAL = 10000 // 10 seconds

// Важные типы активности для отображения
const IMPORTANT_ACTIVITY_TYPES: ActivityType[] = [
  'spin',
  'complete',
  'drop',
  'start_marathon',
  'finish_marathon',
  'event_start',
  'event_end',
  'swap',
  'rematch',
]

export const ActivityFeed = forwardRef<ActivityFeedRef, ActivityFeedProps>(
  ({ marathonId, className = '' }, ref) => {
    const [activities, setActivities] = useState<Activity[]>([])
    const [isLoading, setIsLoading] = useState(true)
    const [isLoadingMore, setIsLoadingMore] = useState(false)
    const [hasMore, setHasMore] = useState(false)
    const [total, setTotal] = useState(0)
    const lastFetchRef = useRef<number>(0)

    const loadActivities = useCallback(async (offset = 0, append = false) => {
      try {
        const response = await feedApi.get(marathonId, ITEMS_PER_PAGE * 2, offset)

        // Фильтруем только важные события
        const filtered = response.items.filter(item =>
          IMPORTANT_ACTIVITY_TYPES.includes(item.type)
        )

        if (append) {
          setActivities(prev => [...prev, ...filtered])
        } else {
          setActivities(filtered)
        }

        setHasMore(response.has_more)
        setTotal(filtered.length)
        lastFetchRef.current = Date.now()
      } catch (error) {
        console.error('Failed to load activity feed:', error)
      }
    }, [marathonId])

    // Expose refresh method
    useImperativeHandle(ref, () => ({
      refresh: () => loadActivities()
    }), [loadActivities])

    // Initial load
    useEffect(() => {
      setIsLoading(true)
      loadActivities().finally(() => setIsLoading(false))
    }, [loadActivities])

    // Polling for new activities
    useEffect(() => {
      const interval = setInterval(() => {
        if (document.visibilityState === 'visible') {
          loadActivities()
        }
      }, POLL_INTERVAL)

      return () => clearInterval(interval)
    }, [loadActivities])

    const handleLoadMore = async () => {
      setIsLoadingMore(true)
      await loadActivities(activities.length, true)
      setIsLoadingMore(false)
    }

    if (isLoading) {
      return (
        <div className={`glass rounded-2xl border border-dark-600 flex flex-col ${className}`}>
          <div className="flex items-center gap-3 px-5 py-4 border-b border-dark-600">
            <div className="w-8 h-8 rounded-lg bg-neon-500/20 flex items-center justify-center">
              <ActivityIcon className="w-4 h-4 text-neon-400" />
            </div>
            <h3 className="font-semibold text-white">Активность</h3>
          </div>
          <div className="flex-1 flex items-center justify-center py-12">
            <Loader2 className="w-8 h-8 animate-spin text-neon-500" />
          </div>
        </div>
      )
    }

    return (
      <div className={`glass rounded-2xl border border-dark-600 flex flex-col overflow-hidden ${className}`}>
        {/* Header */}
        <div className="flex items-center justify-between px-5 py-4 border-b border-dark-600 flex-shrink-0">
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 rounded-lg bg-neon-500/20 flex items-center justify-center">
              <Zap className="w-4 h-4 text-neon-400" />
            </div>
            <div>
              <h3 className="font-semibold text-white">Активность</h3>
              {total > 0 && (
                <p className="text-xs text-gray-500">{total} событий</p>
              )}
            </div>
          </div>
          <div className="w-2 h-2 rounded-full bg-neon-500 animate-pulse" />
        </div>

        {/* Activity list */}
        <div className="flex-1 overflow-y-auto min-h-0 custom-scrollbar">
          {activities.length === 0 ? (
            <div className="px-5 py-12 text-center">
              <div className="w-12 h-12 mx-auto mb-3 rounded-xl bg-dark-700 flex items-center justify-center">
                <Sparkles className="w-6 h-6 text-gray-600" />
              </div>
              <p className="text-gray-400 text-sm">Пока нет активности</p>
            </div>
          ) : (
            <div className="divide-y divide-dark-600/50">
              {activities.map((activity, index) => (
                <ActivityItem
                  key={activity.id}
                  activity={activity}
                  isNew={index === 0}
                />
              ))}
            </div>
          )}

          {/* Load more button */}
          {hasMore && (
            <div className="p-4 border-t border-dark-600/50">
              <button
                onClick={handleLoadMore}
                disabled={isLoadingMore}
                className="w-full py-2.5 text-sm text-gray-400 hover:text-neon-400 transition-colors flex items-center justify-center gap-2 rounded-lg hover:bg-neon-500/5"
              >
                {isLoadingMore ? (
                  <Loader2 className="w-4 h-4 animate-spin" />
                ) : (
                  <>
                    <ChevronDown className="w-4 h-4" />
                    Загрузить ещё
                  </>
                )}
              </button>
            </div>
          )}
        </div>
      </div>
    )
  }
)

ActivityFeed.displayName = 'ActivityFeed'

interface ActivityItemProps {
  activity: Activity
  isNew?: boolean
}

function ActivityItem({ activity, isNew }: ActivityItemProps) {
  const navigate = useNavigate()
  const Icon = getActivityIcon(activity.type)
  const iconColor = getActivityColor(activity.type)
  const isEvent = isEventActivity(activity.type)
  const { title, details, extra } = formatActivityMessage(activity)

  // Get assignment_id, dispute status, and is_redo for complete activities
  const activityData = activity.data as { assignment_id?: number; dispute_status?: string; is_redo?: boolean } | null
  const assignmentId = activity.type === 'complete' && activityData?.assignment_id
    ? activityData.assignment_id
    : null
  const disputeStatus = activity.type === 'complete' && activityData?.dispute_status
    ? activityData.dispute_status
    : null
  const isRedo = activity.type === 'complete' && activityData?.is_redo === true

  // Determine accent color based on activity type
  const getAccentConfig = () => {
    switch (activity.type) {
      case 'spin':
        return { border: 'border-l-accent-500', bg: 'bg-accent-500/5' }
      case 'complete':
        return { border: 'border-l-green-500', bg: 'bg-green-500/5' }
      case 'drop':
        return { border: 'border-l-red-500', bg: 'bg-red-500/5' }
      case 'start_marathon':
      case 'event_start':
        return { border: 'border-l-yellow-500', bg: 'bg-yellow-500/5' }
      case 'finish_marathon':
      case 'event_end':
        return { border: 'border-l-gray-500', bg: 'bg-gray-500/5' }
      case 'swap':
      case 'rematch':
        return { border: 'border-l-neon-500', bg: 'bg-neon-500/5' }
      default:
        return { border: 'border-l-dark-600', bg: '' }
    }
  }

  const accent = getAccentConfig()

  if (isEvent) {
    return (
      <div className={`
        px-5 py-4 border-l-2 transition-colors
        ${accent.border} ${accent.bg}
        hover:bg-dark-700/30
      `}>
        <div className="flex items-center gap-2 mb-1.5">
          <div className={`w-6 h-6 rounded-md flex items-center justify-center ${
            activity.type === 'event_start' ? 'bg-yellow-500/20' : 'bg-gray-500/20'
          }`}>
            <Icon className={`w-3.5 h-3.5 ${iconColor}`} />
          </div>
          <span className={`text-sm font-semibold ${
            activity.type === 'event_start' ? 'text-yellow-400' : 'text-gray-400'
          }`}>
            {title}
          </span>
        </div>
        {details && (
          <div className={`text-sm ml-8 ${
            activity.type === 'event_start' ? 'text-yellow-200/80' : 'text-gray-500'
          }`}>
            {details}
          </div>
        )}
        <div className="text-xs text-gray-600 mt-2 ml-8">
          {formatRelativeTime(activity.created_at)}
        </div>
      </div>
    )
  }

  return (
    <div className={`
      px-5 py-4 border-l-2 transition-all duration-200
      ${accent.border} ${isNew ? accent.bg : ''}
      hover:bg-dark-700/30 group
    `}>
      <div className="flex items-start gap-3">
        {/* Avatar */}
        <Link to={`/users/${activity.user.id}`} className="flex-shrink-0 relative" onClick={(e) => e.stopPropagation()}>
          <UserAvatar
            userId={activity.user.id}
            hasAvatar={!!activity.user.avatar_url}
            nickname={activity.user.nickname}
            size="sm"
            frame={activity.user.equipped_frame}
            telegramAvatarUrl={activity.user.telegram_avatar_url}
          />
          {/* Activity type badge */}
          <div className={`
            absolute -bottom-1 -right-1 w-5 h-5 rounded-full flex items-center justify-center
            border-2 border-dark-800
            ${activity.type === 'complete' ? 'bg-green-500' :
              activity.type === 'drop' ? 'bg-red-500' :
              activity.type === 'spin' ? 'bg-accent-500' :
              'bg-neon-500'}
          `}>
            <Icon className="w-2.5 h-2.5 text-white" />
          </div>
        </Link>

        {/* Content */}
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 flex-wrap">
            <Link
              to={`/users/${activity.user.id}`}
              className="text-sm font-semibold hover:text-neon-400 transition-colors"
              onClick={(e) => e.stopPropagation()}
            >
              <StyledNickname user={activity.user} />
            </Link>
            <span className="text-xs text-gray-600">
              {formatRelativeTime(activity.created_at)}
            </span>
          </div>
          <div className="flex items-center gap-1.5 mt-1">
            <span className="text-sm text-gray-300">{title}</span>
          </div>
          {details && (
            <div className="text-sm text-gray-500 mt-1">
              {details}
            </div>
          )}
          {extra && (
            <div className="text-xs text-gray-600 mt-1">
              {extra}
            </div>
          )}
          {/* Details button and dispute indicator for complete activities */}
          {assignmentId && (
            <div className="flex items-center gap-3 mt-2">
              <button
                onClick={() => navigate(`/assignments/${assignmentId}`)}
                className="text-xs text-neon-400 hover:text-neon-300 flex items-center gap-1.5 px-2 py-1 rounded-md hover:bg-neon-500/10 transition-colors"
              >
                <ExternalLink className="w-3 h-3" />
                Детали
              </button>
              {isRedo && (
                <span className="text-xs text-purple-400 flex items-center gap-1.5 px-2 py-1 rounded-md bg-purple-500/10">
                  <Zap className="w-3 h-3" />
                  Перепрохождение
                </span>
              )}
              {disputeStatus === 'open' && (
                <span className="text-xs text-orange-400 flex items-center gap-1.5 px-2 py-1 rounded-md bg-orange-500/10">
                  <AlertTriangle className="w-3 h-3" />
                  Оспаривается
                </span>
              )}
              {disputeStatus === 'valid' && (
                <span className="text-xs text-red-400 flex items-center gap-1.5 px-2 py-1 rounded-md bg-red-500/10">
                  <AlertTriangle className="w-3 h-3" />
                  Отклонено
                </span>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
