import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { AlertTriangle, X, ChevronDown, ChevronUp, ExternalLink, Check } from 'lucide-react'
import { api, wsClient } from '../lib/api'
import { formatRelativeTime } from '../lib/utils'

interface ErrorItem {
  id: number
  error_hash: string
  module: string
  message: string
  first_seen: string
  last_seen: string
  occurrence_count: number
  log_file: string | null
  line_context: string | null
  dismissed_at: string | null
  viewed_at: string | null
}

export function ErrorBanner() {
  const queryClient = useQueryClient()
  const [isExpanded, setIsExpanded] = useState(false)
  const [isDismissed, setIsDismissed] = useState(false)
  const [displayCount, setDisplayCount] = useState(0)

  // Fetch error count (lightweight polling)
  const { data: errorCount, isSuccess } = useQuery({
    queryKey: ['error-count'],
    queryFn: () => api.getErrorCount(),
    refetchInterval: 30000, // Poll every 30 seconds
    staleTime: 0, // Always fetch fresh on mount
  })

  // Update display count from API response
  useEffect(() => {
    if (isSuccess && errorCount) {
      setDisplayCount(errorCount.since_last_visit)
    }
  }, [isSuccess, errorCount])

  // Fetch detailed errors when expanded - only show errors since last visit
  const { data: errors, refetch: refetchErrors } = useQuery({
    queryKey: ['recent-errors'],
    queryFn: () => api.getRecentErrors(10, false, true),
    enabled: isExpanded,
  })

  // Listen for real-time error alerts via WebSocket
  useEffect(() => {
    const unsubscribeError = wsClient.on('error_alert', (data: { count?: number; new_count?: number }) => {
      // New errors arrived - show banner again
      setIsDismissed(false)

      // Add new errors to display count
      const newCount = data.new_count || 0
      if (newCount > 0) {
        setDisplayCount(prev => prev + newCount)
      }

      // Refresh detailed list if expanded
      if (isExpanded) {
        queryClient.invalidateQueries({ queryKey: ['recent-errors'] })
      }
    })

    return () => {
      unsubscribeError()
    }
  }, [queryClient, isExpanded])

  // Dismiss mutation
  const dismissMutation = useMutation({
    mutationFn: (errorIds: number[]) => api.dismissErrors(errorIds),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['recent-errors'] })
    },
  })

  // Mark viewed mutation - also updates visit timestamp
  const markViewedMutation = useMutation({
    mutationFn: async () => {
      await api.markErrorsViewed()
      await api.updateDashboardVisit()
    },
    onSuccess: () => {
      setDisplayCount(0)
      setIsDismissed(true)
      queryClient.invalidateQueries({ queryKey: ['error-count'] })
    },
  })

  // Don't show if no errors or dismissed
  if (isDismissed || displayCount === 0) {
    return null
  }

  const handleDismissAll = () => {
    if (errors?.errors) {
      const errorIds = errors.errors.map(e => e.id)
      dismissMutation.mutate(errorIds)
    }
    setDisplayCount(0)
    setIsDismissed(true)
  }

  const handleMarkViewed = () => {
    markViewedMutation.mutate()
  }

  const handleDismissBanner = () => {
    // Just hide the banner, don't mark as viewed
    setIsDismissed(true)
  }

  const handleDismissSingle = (errorId: number) => {
    dismissMutation.mutate([errorId])
    setDisplayCount(prev => Math.max(0, prev - 1))
    setTimeout(() => refetchErrors(), 500)
  }

  // Build link to logs page with timestamp filter
  const getLogLink = (error: ErrorItem) => {
    const timestamp = error.last_seen
    return `/logs?filter=${encodeURIComponent(error.module)}&time=${encodeURIComponent(timestamp)}`
  }

  return (
    <div className="bg-gradient-to-r from-red-50 to-orange-50 dark:from-red-900/20 dark:to-orange-900/20 rounded-lg shadow-sm border border-red-200 dark:border-red-800 overflow-hidden">
      {/* Main Banner */}
      <div className="p-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-3 flex-1">
            <div className="relative flex-shrink-0">
              <AlertTriangle className="w-6 h-6 text-red-600 dark:text-red-400" />
              <div className="absolute -top-1 -right-1 w-4 h-4 bg-red-500 rounded-full flex items-center justify-center">
                <span className="text-[10px] font-bold text-white">
                  {displayCount > 9 ? '9+' : displayCount}
                </span>
              </div>
            </div>
            <div className="flex-1 min-w-0">
              <h3 className="text-sm font-semibold text-red-900 dark:text-red-100">
                {displayCount} New Error{displayCount !== 1 ? 's' : ''} Detected
              </h3>
              <p className="text-xs text-red-700 dark:text-red-300 mt-0.5">
                Since your last dashboard visit
              </p>
            </div>
          </div>
          <div className="flex items-center space-x-2">
            <button
              onClick={() => setIsExpanded(!isExpanded)}
              className="flex items-center space-x-1 px-3 py-1.5 text-sm font-medium text-red-700 dark:text-red-300 hover:bg-red-100 dark:hover:bg-red-900/30 rounded-md transition-colors"
            >
              <span>{isExpanded ? 'Hide' : 'View'} Details</span>
              {isExpanded ? (
                <ChevronUp className="w-4 h-4" />
              ) : (
                <ChevronDown className="w-4 h-4" />
              )}
            </button>
            <button
              onClick={handleMarkViewed}
              disabled={markViewedMutation.isPending}
              className="flex items-center space-x-1 px-3 py-1.5 text-sm font-medium text-red-700 dark:text-red-300 hover:bg-red-100 dark:hover:bg-red-900/30 rounded-md transition-colors disabled:opacity-50"
              title="Mark all as viewed and dismiss banner"
            >
              <Check className="w-4 h-4" />
              <span className="hidden sm:inline">Mark Viewed</span>
            </button>
            <button
              onClick={handleDismissBanner}
              className="p-1.5 text-red-600 dark:text-red-400 hover:bg-red-100 dark:hover:bg-red-900/30 rounded-md transition-colors"
              title="Dismiss banner (errors remain unviewed)"
            >
              <X className="w-4 h-4" />
            </button>
          </div>
        </div>
      </div>

      {/* Expanded Error List */}
      {isExpanded && errors?.errors && (
        <div className="border-t border-red-200 dark:border-red-800 bg-white/50 dark:bg-slate-900/50">
          <div className="max-h-64 overflow-y-auto">
            {errors.errors.length > 0 ? (
              <div className="divide-y divide-red-100 dark:divide-red-900/50">
                {errors.errors.map((error) => (
                  <div
                    key={error.id}
                    className="p-3 hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors"
                  >
                    <div className="flex items-start justify-between gap-3">
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center space-x-2 mb-1">
                          <span className="px-2 py-0.5 text-xs font-medium bg-red-100 dark:bg-red-900/50 text-red-700 dark:text-red-300 rounded">
                            {error.module}
                          </span>
                          {error.occurrence_count > 1 && (
                            <span className="text-xs text-red-600 dark:text-red-400">
                              x{error.occurrence_count}
                            </span>
                          )}
                          <span className="text-xs text-slate-500 dark:text-slate-400">
                            {formatRelativeTime(error.last_seen)}
                          </span>
                        </div>
                        <p className="text-sm text-slate-700 dark:text-slate-300 break-words">
                          {error.message.length > 150
                            ? error.message.substring(0, 147) + '...'
                            : error.message}
                        </p>
                      </div>
                      <div className="flex items-center space-x-1 flex-shrink-0">
                        <Link
                          to={getLogLink(error)}
                          className="p-1.5 text-slate-500 hover:text-blue-600 dark:text-slate-400 dark:hover:text-blue-400 hover:bg-slate-100 dark:hover:bg-slate-800 rounded transition-colors"
                          title="View in logs"
                        >
                          <ExternalLink className="w-4 h-4" />
                        </Link>
                        <button
                          onClick={() => handleDismissSingle(error.id)}
                          disabled={dismissMutation.isPending}
                          className="p-1.5 text-slate-500 hover:text-green-600 dark:text-slate-400 dark:hover:text-green-400 hover:bg-slate-100 dark:hover:bg-slate-800 rounded transition-colors"
                          title="Dismiss this error"
                        >
                          <Check className="w-4 h-4" />
                        </button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="p-4 text-center text-slate-500 dark:text-slate-400 text-sm">
                No recent errors to display
              </div>
            )}
          </div>

          {/* Footer Actions */}
          {errors.errors.length > 0 && (
            <div className="p-3 border-t border-red-100 dark:border-red-900/50 bg-red-50/50 dark:bg-red-950/30 flex items-center justify-between">
              <Link
                to="/logs?level=error"
                className="text-sm font-medium text-red-700 dark:text-red-300 hover:text-red-800 dark:hover:text-red-200 flex items-center space-x-1"
              >
                <span>View All Logs</span>
                <ExternalLink className="w-3.5 h-3.5" />
              </Link>
              <button
                onClick={handleDismissAll}
                disabled={dismissMutation.isPending}
                className="px-3 py-1.5 text-sm font-medium bg-red-600 hover:bg-red-700 disabled:bg-red-400 text-white rounded-md transition-colors flex items-center space-x-1"
              >
                <Check className="w-4 h-4" />
                <span>Dismiss All</span>
              </button>
            </div>
          )}
        </div>
      )}
    </div>
  )
}
