'use client'

import { useState } from 'react'
import {
  AlertCircle,
  AlertTriangle,
  Info,
  Zap,
  CheckCircle,
  Loader2,
  Filter,
  Server,
  Clock,
  ChevronDown,
  ChevronUp
} from 'lucide-react'
import { useDetectedErrors, useAcknowledgeError, useClientServers } from '@/hooks/use-enterprise-clients'
import type { ErrorSeverity } from '@/types/api'

interface EnterpriseDetectedErrorsPanelProps {
  clientId: string
  serverId?: string // Optional: filter to a specific server
  limit?: number // Optional: limit number of errors shown
}

const SEVERITY_CONFIG: Record<ErrorSeverity, { icon: React.ElementType; color: string; bg: string; border: string }> = {
  INFO: { icon: Info, color: 'text-blue-600', bg: 'bg-blue-50', border: 'border-blue-200' },
  WARNING: { icon: AlertTriangle, color: 'text-yellow-600', bg: 'bg-yellow-50', border: 'border-yellow-200' },
  ERROR: { icon: AlertCircle, color: 'text-red-600', bg: 'bg-red-50', border: 'border-red-200' },
  CRITICAL: { icon: Zap, color: 'text-purple-600', bg: 'bg-purple-50', border: 'border-purple-200' },
}

export function EnterpriseDetectedErrorsPanel({
  clientId,
  serverId,
  limit = 50,
}: EnterpriseDetectedErrorsPanelProps) {
  const [severityFilter, setSeverityFilter] = useState<ErrorSeverity | 'ALL'>('ALL')
  const [showAcknowledged, setShowAcknowledged] = useState(false)
  const [serverFilter, setServerFilter] = useState<string>(serverId || 'ALL')
  const [expandedErrors, setExpandedErrors] = useState<Set<string>>(new Set())

  const { data: servers } = useClientServers(clientId)
  const { data: errors, isLoading, refetch } = useDetectedErrors(clientId, {
    serverId: serverFilter !== 'ALL' ? serverFilter : undefined,
    severity: severityFilter !== 'ALL' ? severityFilter : undefined,
    acknowledged: showAcknowledged ? undefined : false,
    limit,
  })
  const acknowledgeError = useAcknowledgeError()

  const handleAcknowledge = async (errorId: string) => {
    try {
      await acknowledgeError.mutateAsync({ clientId, errorId })
    } catch (error) {
      console.error('Failed to acknowledge error:', error)
    }
  }

  const toggleExpanded = (errorId: string) => {
    const newExpanded = new Set(expandedErrors)
    if (newExpanded.has(errorId)) {
      newExpanded.delete(errorId)
    } else {
      newExpanded.add(errorId)
    }
    setExpandedErrors(newExpanded)
  }

  const formatTimestamp = (timestamp: Date | string) => {
    const date = timestamp instanceof Date ? timestamp : new Date(timestamp)
    const now = new Date()
    const diff = now.getTime() - date.getTime()
    const minutes = Math.floor(diff / 60000)
    const hours = Math.floor(diff / 3600000)
    const days = Math.floor(diff / 86400000)

    if (minutes < 1) return 'Just now'
    if (minutes < 60) return `${minutes}m ago`
    if (hours < 24) return `${hours}h ago`
    if (days < 7) return `${days}d ago`
    return date.toLocaleDateString()
  }

  const unacknowledgedCount = errors?.filter(e => !e.acknowledgedAt).length || 0
  const criticalCount = errors?.filter(e => e.rule?.severity === 'CRITICAL' && !e.acknowledgedAt).length || 0

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-32">
        <Loader2 className="h-6 w-6 animate-spin text-gray-400" />
      </div>
    )
  }

  return (
    <div className="space-y-4">
      {/* Header with Stats */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <p className="text-sm text-gray-500">
            {unacknowledgedCount} unacknowledged error{unacknowledgedCount !== 1 ? 's' : ''}
            {criticalCount > 0 && (
              <span className="ml-2 text-red-600 font-medium">
                ({criticalCount} critical)
              </span>
            )}
          </p>
        </div>
        <button
          onClick={() => refetch()}
          className="text-sm text-blue-600 hover:text-blue-700"
        >
          Refresh
        </button>
      </div>

      {/* Filters */}
      <div className="flex flex-wrap items-center gap-3 p-3 bg-gray-50 rounded-lg">
        <div className="flex items-center gap-2">
          <Filter className="h-4 w-4 text-gray-400" />
          <span className="text-sm text-gray-500">Filters:</span>
        </div>

        {/* Server Filter (only if not pre-filtered) */}
        {!serverId && servers && servers.length > 0 && (
          <select
            value={serverFilter}
            onChange={(e) => setServerFilter(e.target.value)}
            className="text-sm border border-gray-300 rounded-md px-2 py-1"
          >
            <option value="ALL">All Servers</option>
            {servers.map((server) => (
              <option key={server.id} value={server.id}>
                {server.nickname || server.netcupServerId}
              </option>
            ))}
          </select>
        )}

        {/* Severity Filter */}
        <select
          value={severityFilter}
          onChange={(e) => setSeverityFilter(e.target.value as ErrorSeverity | 'ALL')}
          className="text-sm border border-gray-300 rounded-md px-2 py-1"
        >
          <option value="ALL">All Severities</option>
          <option value="CRITICAL">Critical</option>
          <option value="ERROR">Error</option>
          <option value="WARNING">Warning</option>
          <option value="INFO">Info</option>
        </select>

        {/* Show Acknowledged Toggle */}
        <label className="flex items-center gap-2 text-sm text-gray-600 cursor-pointer">
          <input
            type="checkbox"
            checked={showAcknowledged}
            onChange={(e) => setShowAcknowledged(e.target.checked)}
            className="rounded border-gray-300"
          />
          Show acknowledged
        </label>
      </div>

      {/* Errors List */}
      {errors && errors.length > 0 ? (
        <div className="space-y-3">
          {errors.map((error) => {
            const severity = error.rule?.severity || 'WARNING'
            const config = SEVERITY_CONFIG[severity]
            const Icon = config.icon
            const isExpanded = expandedErrors.has(error.id)

            return (
              <div
                key={error.id}
                className={`rounded-lg border p-4 ${config.bg} ${config.border} ${
                  error.acknowledgedAt ? 'opacity-60' : ''
                }`}
              >
                <div className="flex items-start justify-between gap-4">
                  <div className="flex items-start gap-3 flex-1 min-w-0">
                    <div className={`p-1.5 rounded-lg bg-white`}>
                      <Icon className={`h-4 w-4 ${config.color}`} />
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 flex-wrap">
                        <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${config.bg} ${config.color} border ${config.border}`}>
                          {severity}
                        </span>
                        <span className="text-sm font-medium text-gray-900">
                          {error.rule?.name || 'Unknown Rule'}
                        </span>
                        {error.acknowledgedAt && (
                          <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-gray-100 text-gray-600">
                            <CheckCircle className="h-3 w-3 mr-1" />
                            Acknowledged
                          </span>
                        )}
                      </div>

                      <div className="mt-1 flex items-center gap-3 text-xs text-gray-500">
                        <span className="flex items-center gap-1">
                          <Clock className="h-3 w-3" />
                          {formatTimestamp(error.timestamp)}
                        </span>
                        {error.server && (
                          <span className="flex items-center gap-1">
                            <Server className="h-3 w-3" />
                            {error.server.nickname || error.server.netcupServerId}
                          </span>
                        )}
                        {error.containerName && (
                          <span className="text-gray-400">
                            Container: {error.containerName}
                          </span>
                        )}
                      </div>

                      {/* Log Line Preview */}
                      <div className="mt-2">
                        <button
                          onClick={() => toggleExpanded(error.id)}
                          className="flex items-center gap-1 text-xs text-gray-500 hover:text-gray-700"
                        >
                          {isExpanded ? (
                            <ChevronUp className="h-3 w-3" />
                          ) : (
                            <ChevronDown className="h-3 w-3" />
                          )}
                          {isExpanded ? 'Hide details' : 'Show details'}
                        </button>

                        {isExpanded && (
                          <div className="mt-2 space-y-2">
                            <div>
                              <p className="text-xs font-medium text-gray-600 mb-1">Log Line:</p>
                              <pre className="text-xs bg-white p-2 rounded border border-gray-200 overflow-x-auto whitespace-pre-wrap font-mono text-gray-800">
                                {error.logLine}
                              </pre>
                            </div>
                            {error.context && (
                              <div>
                                <p className="text-xs font-medium text-gray-600 mb-1">Context:</p>
                                <pre className="text-xs bg-white p-2 rounded border border-gray-200 overflow-x-auto whitespace-pre-wrap font-mono text-gray-600">
                                  {error.context}
                                </pre>
                              </div>
                            )}
                          </div>
                        )}
                      </div>
                    </div>
                  </div>

                  {/* Actions */}
                  <div className="flex items-center gap-2">
                    {!error.acknowledgedAt && (
                      <button
                        onClick={() => handleAcknowledge(error.id)}
                        disabled={acknowledgeError.isPending}
                        className="inline-flex items-center px-2.5 py-1 border border-gray-300 rounded-md text-xs font-medium text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50"
                        title="Acknowledge this error"
                      >
                        {acknowledgeError.isPending ? (
                          <Loader2 className="h-3 w-3 animate-spin" />
                        ) : (
                          <>
                            <CheckCircle className="h-3 w-3 mr-1" />
                            Acknowledge
                          </>
                        )}
                      </button>
                    )}
                  </div>
                </div>
              </div>
            )
          })}
        </div>
      ) : (
        <div className="text-center py-8 text-gray-500">
          <CheckCircle className="h-8 w-8 mx-auto mb-2 text-green-400" />
          <p>No detected errors</p>
          <p className="text-sm mt-1">
            {showAcknowledged
              ? 'No errors match the current filters'
              : 'All errors have been acknowledged'}
          </p>
        </div>
      )}
    </div>
  )
}
