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

interface CookieService {
  id: string
  name: string
  type: 'scraper' | 'paid_content' | 'private_gallery'
  status: 'healthy' | 'expired' | 'missing' | 'down' | 'degraded' | 'unknown' | 'failed'
  last_updated?: string
  last_checked?: string
  message: string
}

const statusConfig: Record<string, { label: string; color: string }> = {
  expired: { label: 'Expired', color: 'bg-red-100 text-red-700 dark:bg-red-900/50 dark:text-red-300' },
  failed: { label: 'Failed', color: 'bg-red-100 text-red-700 dark:bg-red-900/50 dark:text-red-300' },
  down: { label: 'Down', color: 'bg-red-100 text-red-700 dark:bg-red-900/50 dark:text-red-300' },
  degraded: { label: 'Degraded', color: 'bg-amber-100 text-amber-700 dark:bg-amber-900/50 dark:text-amber-300' },
  missing: { label: 'Missing', color: 'bg-slate-100 text-slate-700 dark:bg-slate-700 dark:text-slate-300' },
  unknown: { label: 'Unknown', color: 'bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-400' },
  healthy: { label: 'Healthy', color: 'bg-green-100 text-green-700 dark:bg-green-900/50 dark:text-green-300' },
}

export function CookieHealthBanner() {
  const [isExpanded, setIsExpanded] = useState(false)
  const [isDismissed, setIsDismissed] = useState(false)

  const { data } = useQuery({
    queryKey: ['cookie-health'],
    queryFn: () => api.getCookieHealth(),
    refetchInterval: 60000,
    staleTime: 0,
  })

  // Listen for real-time cookie health alerts
  useEffect(() => {
    const unsubscribe = wsClient.on('cookie_health_alert', () => {
      setIsDismissed(false)
    })
    return () => { unsubscribe() }
  }, [])

  if (isDismissed || !data?.has_issues) {
    return null
  }

  const issueServices = data.services.filter(
    (s: CookieService) => s.status !== 'healthy' && s.status !== 'unknown'
  )

  if (issueServices.length === 0) {
    return null
  }

  const getSettingsLink = (_service: CookieService) => '/scrapers'

  return (
    <div className="bg-gradient-to-r from-amber-50 to-yellow-50 dark:from-amber-900/20 dark:to-yellow-900/20 rounded-lg shadow-sm border border-amber-200 dark:border-amber-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">
              <KeyRound className="w-6 h-6 text-amber-600 dark:text-amber-400" />
              <div className="absolute -top-1 -right-1 w-4 h-4 bg-amber-500 rounded-full flex items-center justify-center">
                <span className="text-[10px] font-bold text-white">
                  {data.issue_count > 9 ? '9+' : data.issue_count}
                </span>
              </div>
            </div>
            <div className="flex-1 min-w-0">
              <h3 className="text-sm font-semibold text-amber-900 dark:text-amber-100">
                {data.issue_count} Cookie/Session Issue{data.issue_count !== 1 ? 's' : ''} Detected
              </h3>
              <p className="text-xs text-amber-700 dark:text-amber-300 mt-0.5">
                Some services may not be downloading properly
              </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-amber-700 dark:text-amber-300 hover:bg-amber-100 dark:hover:bg-amber-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={() => setIsDismissed(true)}
              className="p-1.5 text-amber-600 dark:text-amber-400 hover:bg-amber-100 dark:hover:bg-amber-900/30 rounded-md transition-colors"
              title="Dismiss"
            >
              <X className="w-4 h-4" />
            </button>
          </div>
        </div>
      </div>

      {/* Expanded Service List */}
      {isExpanded && (
        <div className="border-t border-amber-200 dark:border-amber-800 bg-white/50 dark:bg-slate-900/50">
          <div className="max-h-64 overflow-y-auto">
            <div className="divide-y divide-amber-100 dark:divide-amber-900/50">
              {issueServices.map((service: CookieService) => {
                const cfg = statusConfig[service.status] || statusConfig.unknown
                return (
                  <div
                    key={service.id}
                    className="p-3 hover:bg-amber-50 dark:hover:bg-amber-900/20 transition-colors"
                  >
                    <div className="flex items-center justify-between gap-3">
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center space-x-2 mb-1">
                          <span className="font-medium text-sm text-slate-800 dark:text-slate-200">
                            {service.name}
                          </span>
                          <span className="px-1.5 py-0.5 text-[10px] font-medium bg-slate-100 dark:bg-slate-700 text-slate-600 dark:text-slate-300 rounded">
                            {service.type === 'scraper' ? 'Scraper' : service.type === 'private_gallery' ? 'Private Gallery' : 'Paid Content'}
                          </span>
                          <span className={`px-1.5 py-0.5 text-[10px] font-medium rounded ${cfg.color}`}>
                            {cfg.label}
                          </span>
                        </div>
                        <div className="flex items-center space-x-3 text-xs text-slate-500 dark:text-slate-400">
                          {service.last_updated && (
                            <span>Updated {formatRelativeTime(service.last_updated)}</span>
                          )}
                          {service.message && (
                            <span className="truncate max-w-[200px]">{service.message}</span>
                          )}
                        </div>
                      </div>
                      <Link
                        to={getSettingsLink(service)}
                        className="p-1.5 text-slate-500 hover:text-amber-600 dark:text-slate-400 dark:hover:text-amber-400 hover:bg-slate-100 dark:hover:bg-slate-800 rounded transition-colors flex-shrink-0"
                        title="Go to settings"
                      >
                        <ExternalLink className="w-4 h-4" />
                      </Link>
                    </div>
                  </div>
                )
              })}
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
