"use client"

import { useState, useCallback, memo } from "react"
import {
  XCircle,
  AlertCircle,
  AlertTriangle,
  ChevronDown,
} from "lucide-react"
import { CopyButton } from "./copy-button"

interface ErrorContext {
  test_name?: string
  failure_reason?: string
  test_output?: string
  expected?: string
  actual?: string
}

interface TraceError {
  id: string
  error_type: string
  severity: string
  error_message: string
  context: ErrorContext | null
  created_at: Date
}

interface ErrorsSectionProps {
  errors: TraceError[]
}

export const ErrorsSection = memo(function ErrorsSection({ errors }: ErrorsSectionProps) {
  const [expandedErrors, setExpandedErrors] = useState<Set<string>>(new Set())

  const toggleError = useCallback((errorId: string) => {
    setExpandedErrors(prev => {
      const next = new Set(prev)
      if (next.has(errorId)) {
        next.delete(errorId)
      } else {
        next.add(errorId)
      }
      return next
    })
  }, [])

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

  return (
    <div className="bg-white dark:bg-zinc-900 rounded-sm border border-zinc-200 dark:border-zinc-700">
      <div className="p-6 border-b border-zinc-200 dark:border-zinc-700">
        <div className="flex items-center gap-3">
          <AlertCircle className="h-5 w-5 text-red-600 dark:text-red-400" />
          <h2 className="text-xl font-bold text-red-600 dark:text-red-400">Errors</h2>
          <span className="text-red-400 border border-red-600 text-sm px-2.5 py-0.5 rounded-sm font-semibold">
            {errors.length}
          </span>
        </div>
      </div>

      <div className="divide-y divide-zinc-200 dark:divide-zinc-700">
        {errors.map(error => {
          const isExpanded = expandedErrors.has(error.id)
          const isTestFailure = error.error_type === "test_failure"
          const hasContext = error.context && Object.keys(error.context).length > 0

          const SeverityIcon =
            error.severity === "critical" || error.severity === "error" ? XCircle : AlertTriangle

          function getSeverityColor(severity: string): string {
            switch (severity) {
              case "critical":
                return "text-red-400 border border-red-600 px-1.5 py-0.5"
              case "error":
                return "text-orange-400 border border-orange-600 px-1.5 py-0.5"
              default:
                return "text-yellow-400 border border-yellow-600 px-1.5 py-0.5"
            }
          }
          const severityColor = getSeverityColor(error.severity)

          return (
            <div key={error.id} className="border-l-4 border-red-500">
              <div className="w-full p-4 flex items-start gap-3">
                <div
                  role="button"
                  tabIndex={0}
                  onClick={() => toggleError(error.id)}
                  onKeyDown={e => { if (e.key === "Enter" || e.key === " ") toggleError(error.id) }}
                  className="flex items-start gap-3 cursor-pointer hover:opacity-80 flex-1 transition-opacity duration-150"
                >
                  <SeverityIcon className="h-5 w-5 text-red-600 dark:text-red-400 mt-0.5 flex-shrink-0" />
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-1 flex-wrap">
                      <span className="font-semibold text-zinc-900 dark:text-white">
                        {error.error_type}
                      </span>
                      <span className={`text-xs font-semibold rounded-sm ${severityColor}`}>
                        {error.severity}
                      </span>
                      <span className="text-xs text-zinc-500 dark:text-zinc-400 ml-auto">
                        {new Date(error.created_at).toLocaleString()}
                      </span>
                    </div>
                    <p className="text-sm text-zinc-700 dark:text-zinc-300 line-clamp-2">
                      {error.error_message}
                    </p>
                  </div>
                  {(hasContext || isTestFailure) && (
                    <ChevronDown className={`h-4 w-4 text-zinc-400 transition-transform duration-200 ${isExpanded ? '' : '-rotate-90'}`} />
                  )}
                </div>
                <div className="flex items-center gap-2">
                  <CopyButton text={error.error_message} label="error message" size="sm" />
                </div>
              </div>

              {isExpanded && isTestFailure && error.context && (
                <div className="px-4 pb-4 ml-8">
                  <div className="p-4 bg-zinc-50 dark:bg-zinc-800 rounded-sm border border-zinc-200 dark:border-zinc-700">
                    <h4 className="text-sm font-semibold text-red-600 dark:text-red-400 mb-3">
                      Test Failure Details
                    </h4>

                    {error.context.test_name && (
                      <div className="mb-3">
                        <span className="text-xs font-medium text-zinc-600 dark:text-zinc-400 uppercase tracking-wide">
                          Test Name
                        </span>
                        <p className="text-sm text-zinc-900 dark:text-white font-mono mt-1">
                          {error.context.test_name}
                        </p>
                      </div>
                    )}

                    {error.context.failure_reason && (
                      <div className="mb-3">
                        <span className="text-xs font-medium text-zinc-600 dark:text-zinc-400 uppercase tracking-wide">
                          Failure Reason
                        </span>
                        <p className="text-sm text-zinc-900 dark:text-white mt-1 whitespace-pre-wrap">
                          {error.context.failure_reason}
                        </p>
                      </div>
                    )}

                    {error.context.expected && (
                      <div className="mb-3">
                        <span className="text-xs font-medium text-zinc-600 dark:text-zinc-400 uppercase tracking-wide">
                          Expected
                        </span>
                        <pre className="text-xs text-zinc-900 dark:text-white mt-1 bg-white dark:bg-zinc-900 p-2 rounded-sm overflow-x-auto font-mono">
                          {String(error.context.expected)}
                        </pre>
                      </div>
                    )}

                    {error.context.actual && (
                      <div className="mb-3">
                        <span className="text-xs font-medium text-zinc-600 dark:text-zinc-400 uppercase tracking-wide">
                          Actual
                        </span>
                        <pre className="text-xs text-zinc-900 dark:text-white mt-1 bg-white dark:bg-zinc-900 p-2 rounded-sm overflow-x-auto font-mono">
                          {String(error.context.actual)}
                        </pre>
                      </div>
                    )}

                    {error.context.test_output && (
                      <div>
                        <span className="text-xs font-medium text-zinc-600 dark:text-zinc-400 uppercase tracking-wide">
                          Test Output
                        </span>
                        <pre className="text-xs text-zinc-900 dark:text-white mt-1 bg-white dark:bg-zinc-900 p-2 rounded-sm overflow-x-auto whitespace-pre-wrap font-mono max-h-48">
                          {String(error.context.test_output)}
                        </pre>
                      </div>
                    )}
                  </div>
                </div>
              )}

              {isExpanded && !isTestFailure && hasContext && (
                <div className="px-4 pb-4 ml-8">
                  <div className="p-4 bg-zinc-50 dark:bg-zinc-900 rounded-sm border border-zinc-200 dark:border-zinc-700">
                    <span className="text-xs font-medium text-zinc-600 dark:text-zinc-400 uppercase tracking-wide">
                      Context
                    </span>
                    <pre className="text-xs text-zinc-900 dark:text-white mt-2 overflow-auto whitespace-pre-wrap font-mono max-h-48">
                      {JSON.stringify(error.context, null, 2)}
                    </pre>
                  </div>
                </div>
              )}
            </div>
          )
        })}
      </div>
    </div>
  )
})