"use client"

import { useState, useCallback, type ChangeEvent } from "react"
import { Search, Loader2, CheckCircle, FileText } from "lucide-react"
import { useRouter } from "next/navigation"

interface TraceSearchProps {
  initialTraceId?: string
  isLoading?: boolean
  hasResults?: boolean
}

export function TraceSearch({ initialTraceId = "", isLoading = false, hasResults = false }: TraceSearchProps) {
  const [traceId, setTraceId] = useState(initialTraceId)
  const router = useRouter()

  const handleChange = useCallback((e: ChangeEvent<HTMLInputElement>) => {
    setTraceId(e.target.value)
  }, [])

  const handleSearch = useCallback(() => {
    const trimmedId = traceId.trim()
    if (!trimmedId) return

    const params = new URLSearchParams(window.location.search)
    params.set("trace_id", trimmedId)
    router.push(`/observability?${params.toString()}`)
  }, [traceId, router])

  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent<HTMLInputElement>) => {
      if (e.key === "Enter") {
        handleSearch()
      }
    },
    [handleSearch],
  )

  function getInputBorderClass(): string {
    if (hasResults) {
      return "border-green-500 dark:border-green-500 focus:ring-green-500"
    }
    return "border-zinc-300 dark:border-zinc-600 focus:ring-blue-500"
  }

  return (
    <div className="w-full max-w-2xl mx-auto">
      <div className="relative flex items-center gap-3">
        <div className="relative flex-1">
          <input
            type="text"
            value={traceId}
            onChange={handleChange}
            onKeyDown={handleKeyDown}
            placeholder="Enter trace ID..."
            className={`w-full px-4 py-3 pl-11 ${hasResults ? "pr-11" : ""} text-base rounded-md border ${getInputBorderClass()} bg-white dark:bg-zinc-950 text-zinc-900 dark:text-zinc-50 placeholder-zinc-400 dark:placeholder-zinc-500 focus:outline-none focus:ring-2 focus:border-transparent transition-all duration-150`}
            aria-label="Trace ID"
          />
          <Search className="absolute left-4 top-1/2 -translate-y-1/2 h-4 w-4 text-zinc-400" />
          {hasResults && (
            <CheckCircle className="absolute right-4 top-1/2 -translate-y-1/2 h-5 w-5 text-green-500" />
          )}
        </div>
        <button
          onClick={handleSearch}
          disabled={!traceId.trim() || isLoading}
          className="px-6 py-3 bg-blue-600 hover:bg-blue-700 disabled:bg-blue-400 disabled:cursor-not-allowed text-white font-medium rounded-md transition-colors duration-150 flex items-center gap-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
        >
          {isLoading ? (
            <>
              <Loader2 className="h-5 w-5 animate-spin" />
              Loading
            </>
          ) : (
            "Search"
          )}
        </button>
        {hasResults && (
          <a
            href={`/observability/llm-export?trace_id=${encodeURIComponent(traceId.trim())}`}
            target="_blank"
            rel="noopener noreferrer"
            className="px-4 py-3 bg-zinc-100 hover:bg-zinc-200 dark:bg-zinc-700 dark:hover:bg-zinc-600 text-zinc-700 dark:text-zinc-200 font-medium rounded-md transition-colors duration-150 flex items-center gap-2 focus:outline-none focus:ring-2 focus:ring-zinc-500 focus:ring-offset-2 text-sm whitespace-nowrap"
            title="Export trace as text for LLM analysis"
          >
            <FileText className="h-4 w-4" />
            LLM Export
          </a>
        )}
      </div>
      {!hasResults && (
        <p className="mt-2 text-sm text-zinc-500 dark:text-zinc-400">
          Paste or type a trace ID to view all associated LLM calls, candidates, and errors
        </p>
      )}
    </div>
  )
}