import Link from "next/link"
import { Metadata } from "next"
import { notFound } from "next/navigation"
import { CheckCircle, XCircle, Hash, FileText, Code, AlertTriangle } from "lucide-react"
import { prisma } from "@/lib/prisma"
import { StatCard } from "@/components/observability/stat-card"
import { InfoIcon } from "@/components/observability/info-icon"
import { CopyButton } from "@/components/observability/copy-button"
import { ParsedResponseView } from "@/components/observability/parsed-response-view"

interface LLMCallDetailPageProps {
  params: Promise<{
    id: string
  }>
}

export async function generateMetadata(props: LLMCallDetailPageProps): Promise<Metadata> {
  const params = await props.params
  return {
    title: `LLM Call ${params.id.substring(0, 8)} - Observability`,
    description: "View LLM call details for prompt engineering analysis",
  }
}

export default async function LLMCallDetailPage(props: LLMCallDetailPageProps) {
  const params = await props.params
  // Fetch LLM call details and related errors in parallel
  const [llmCall, relatedErrors] = await Promise.all([
    prisma.llm_calls.findUnique({
      where: { id: params.id },
      select: {
        id: true,
        trace_id: true,
        call_type: true,
        model_name: true,
        system_prompt: true,
        user_prompt: true,
        temperature: true,
        n_candidates: true,
        raw_response: true,
        prompt_tokens: true,
        completion_tokens: true,
        total_tokens: true,
        llm_cost: true,
        latency_ms: true,
        status: true,
        error_type: true,
        error_message: true,
        parsing_status: true,
        candidates_generated: true,
        candidates_valid: true,
        parsing_errors: true,
        created_at: true,
      },
    }),
    prisma.optimization_errors.findMany({
      where: { llm_call_id: params.id },
      orderBy: { created_at: "desc" },
      select: {
        id: true,
        error_type: true,
        severity: true,
        error_message: true,
        context: true,
        created_at: true,
      },
    }),
  ])

  if (!llmCall) {
    notFound()
  }

  return (
    <div className="container mx-auto px-4 py-8">
      {/* Header */}
      <div className="mb-8">
        {/* Breadcrumb */}
        <div className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400 mb-4">
          <Link
            href="/observability/llm-calls"
            className="hover:text-blue-600 dark:hover:text-blue-400"
          >
            LLM Calls
          </Link>
          <span>/</span>
          <span className="text-gray-900 dark:text-white font-mono">
            {llmCall.id.substring(0, 8)}...
          </span>
        </div>

        <h1 className="text-3xl font-bold tracking-tight text-gray-900 dark:text-white mb-3">
          LLM Call Detail
        </h1>

        {/* ID and Trace with Copy Buttons */}
        <div className="space-y-2">
          <div className="flex items-center gap-2">
            <span className="text-sm text-gray-600 dark:text-gray-400">Call ID:</span>
            <code className="text-sm font-mono text-gray-900 dark:text-white bg-gray-100 dark:bg-gray-700 px-2 py-1 rounded">
              {llmCall.id}
            </code>
            <CopyButton text={llmCall.id} label="call ID" size="sm" />
          </div>
          {llmCall.trace_id && (
            <div className="flex items-center gap-2">
              <span className="text-sm text-gray-600 dark:text-gray-400">Trace:</span>
              <Link
                href={`/observability/trace/${llmCall.trace_id}`}
                className="text-sm font-mono text-blue-600 dark:text-blue-400 hover:underline bg-gray-100 dark:bg-gray-700 px-2 py-1 rounded"
              >
                {llmCall.trace_id}
              </Link>
              <CopyButton text={llmCall.trace_id} label="trace ID" size="sm" />
            </div>
          )}
        </div>
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-5 mb-8">
        <StatCard
          label="Status"
          value={llmCall.status}
          helpText="Call outcome: success, failed, partial_success, or in_progress"
          icon={
            llmCall.status === "success"
              ? "CheckCircle2"
              : llmCall.status === "failed"
                ? "AlertTriangle"
                : "Clock"
          }
          variant={
            llmCall.status === "success"
              ? "success"
              : llmCall.status === "failed"
                ? "error"
                : "warning"
          }
        />
        <StatCard
          label="Latency"
          value={llmCall.latency_ms ? `${llmCall.latency_ms}ms` : "N/A"}
          helpText="API response time in milliseconds. Time from request to completion."
          icon="Clock"
        />
        <StatCard
          label="Tokens"
          value={llmCall.total_tokens?.toLocaleString() ?? "N/A"}
          helpText="Total tokens (prompt + completion) used in this call"
          icon="Database"
        />
        <StatCard
          label="Cost"
          value={llmCall.llm_cost ? `$${llmCall.llm_cost.toFixed(4)}` : "N/A"}
          helpText="Cost in USD for this specific call based on model pricing"
          icon="DollarSign"
        />
      </div>

      {/* Metadata */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-8 border border-gray-200 dark:border-gray-700">
        <h2 className="text-xl font-semibold mb-4 text-gray-900 dark:text-white">Metadata</h2>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="flex items-start gap-2">
            <div className="flex-1">
              <div className="flex items-center gap-1.5 mb-1">
                <span className="text-sm font-medium text-gray-600 dark:text-gray-400">
                  Call Type
                </span>
                <InfoIcon
                  content="Purpose of this LLM operation (optimization, validation, line_profiler, etc.)"
                  side="top"
                />
              </div>
              <span className="font-semibold text-gray-900 dark:text-gray-100">
                {llmCall.call_type}
              </span>
            </div>
          </div>
          <div className="flex items-start gap-2">
            <div className="flex-1">
              <div className="flex items-center gap-1.5 mb-1">
                <span className="text-sm font-medium text-gray-600 dark:text-gray-400">Model</span>
                <InfoIcon content="AI model and version used for this call" side="top" />
              </div>
              <span className="font-semibold text-gray-900 dark:text-gray-100">
                {llmCall.model_name}
              </span>
            </div>
          </div>
          <div className="flex items-start gap-2">
            <div className="flex-1">
              <div className="flex items-center gap-1.5 mb-1">
                <span className="text-sm font-medium text-gray-600 dark:text-gray-400">
                  Temperature
                </span>
                <InfoIcon
                  content="Randomness setting (0=deterministic, 1=creative). Controls output variability."
                  side="top"
                />
              </div>
              <span className="font-semibold text-gray-900 dark:text-gray-100">
                {llmCall.temperature || "default"}
              </span>
            </div>
          </div>
          <div className="flex items-start gap-2">
            <div className="flex-1">
              <div className="flex items-center gap-1.5 mb-1">
                <span className="text-sm font-medium text-gray-600 dark:text-gray-400">
                  Candidates Requested
                </span>
                <InfoIcon content="Number of code variations requested from the model" side="top" />
              </div>
              <span className="font-semibold text-gray-900 dark:text-gray-100">
                {llmCall.n_candidates || "N/A"}
              </span>
            </div>
          </div>
          <div className="flex items-start gap-2">
            <div className="flex-1">
              <div className="flex items-center gap-1.5 mb-1">
                <span className="text-sm font-medium text-gray-600 dark:text-gray-400">
                  Created
                </span>
                <InfoIcon content="When this call was initiated" side="top" />
              </div>
              <span className="font-semibold text-gray-900 dark:text-gray-100">
                {new Date(llmCall.created_at).toLocaleString()}
              </span>
            </div>
          </div>
          <div className="flex items-start gap-2">
            <div className="flex-1">
              <div className="flex items-center gap-1.5 mb-1">
                <span className="text-sm font-medium text-gray-600 dark:text-gray-400">
                  Parsing Status
                </span>
                <InfoIcon
                  content="Whether model output was successfully parsed into usable code candidates"
                  side="top"
                />
              </div>
              <span
                className={`font-semibold ${
                  llmCall.parsing_status === "success"
                    ? "text-green-600 dark:text-green-400"
                    : "text-red-600 dark:text-red-400"
                }`}
              >
                {llmCall.parsing_status || "N/A"}
              </span>
            </div>
          </div>
        </div>
      </div>

      {/* Token Breakdown */}
      {llmCall.prompt_tokens && (
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-8 border border-gray-200 dark:border-gray-700">
          <div className="flex items-center gap-2 mb-4">
            <Hash className="h-5 w-5 text-gray-600 dark:text-gray-400" />
            <h2 className="text-xl font-semibold text-gray-900 dark:text-white">Token Usage</h2>
          </div>

          {/* Visual Token Ratio Bar */}
          <div className="mb-6">
            <div className="flex items-center gap-2 mb-2">
              <span className="text-sm font-medium text-gray-600 dark:text-gray-400">
                Token Distribution
              </span>
              <InfoIcon content="Visual breakdown of prompt vs completion tokens" side="top" />
            </div>
            <div className="flex h-8 rounded-lg overflow-hidden border border-gray-200 dark:border-gray-600">
              {(() => {
                const promptTokens = llmCall.prompt_tokens ?? 0
                const completionTokens = llmCall.completion_tokens ?? 0
                const totalTokens = llmCall.total_tokens ?? promptTokens + completionTokens
                // Use 1 as fallback only for division to prevent division by zero
                const safeTotalTokens = totalTokens || 1
                const promptPercent = Math.round((promptTokens / safeTotalTokens) * 100)
                const completionPercent = Math.round((completionTokens / safeTotalTokens) * 100)

                return (
                  <>
                    <div
                      className="bg-blue-500 dark:bg-blue-600 flex items-center justify-center text-white text-xs font-semibold"
                      style={{ width: `${promptPercent}%` }}
                    >
                      {promptPercent > 0 && <span className="px-2">{promptPercent}%</span>}
                    </div>
                    <div
                      className="bg-green-500 dark:bg-green-600 flex items-center justify-center text-white text-xs font-semibold"
                      style={{ width: `${completionPercent}%` }}
                    >
                      {completionPercent > 0 && <span className="px-2">{completionPercent}%</span>}
                    </div>
                  </>
                )
              })()}
            </div>
          </div>

          <div className="grid grid-cols-3 gap-6">
            {(() => {
              const promptTokens = llmCall.prompt_tokens ?? 0
              const completionTokens = llmCall.completion_tokens ?? 0
              const totalTokens = llmCall.total_tokens ?? promptTokens + completionTokens

              return (
                <>
                  <div>
                    <div className="flex items-center gap-1.5 mb-2">
                      <div className="w-3 h-3 rounded-sm bg-blue-500 dark:bg-blue-600"></div>
                      <span className="text-sm font-medium text-gray-600 dark:text-gray-400">
                        Prompt Tokens
                      </span>
                    </div>
                    <div className="text-2xl font-bold text-gray-900 dark:text-white">
                      {promptTokens.toLocaleString()}
                    </div>
                  </div>
                  <div>
                    <div className="flex items-center gap-1.5 mb-2">
                      <div className="w-3 h-3 rounded-sm bg-green-500 dark:bg-green-600"></div>
                      <span className="text-sm font-medium text-gray-600 dark:text-gray-400">
                        Completion Tokens
                      </span>
                    </div>
                    <div className="text-2xl font-bold text-gray-900 dark:text-white">
                      {completionTokens.toLocaleString()}
                    </div>
                  </div>
                  <div>
                    <div className="flex items-center gap-1.5 mb-2">
                      <span className="text-sm font-medium text-gray-600 dark:text-gray-400">
                        Total Tokens
                      </span>
                    </div>
                    <div className="text-2xl font-bold text-gray-900 dark:text-white">
                      {totalTokens.toLocaleString()}
                    </div>
                  </div>
                </>
              )
            })()}
          </div>
        </div>
      )}

      {/* Parsing Results */}
      {llmCall.candidates_generated !== null && (
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-8 border border-gray-200 dark:border-gray-700">
          <div className="flex items-center gap-2 mb-4">
            <Code className="h-5 w-5 text-gray-600 dark:text-gray-400" />
            <h2 className="text-xl font-semibold text-gray-900 dark:text-white">Parsing Results</h2>
            <InfoIcon
              content="Results from parsing the model's response into code candidates"
              side="top"
            />
          </div>
          <div className="grid grid-cols-2 gap-6">
            <div>
              <div className="flex items-center gap-1.5 mb-2">
                <span className="text-sm font-medium text-gray-600 dark:text-gray-400">
                  Candidates Generated
                </span>
              </div>
              <div className="text-2xl font-bold text-gray-900 dark:text-white">
                {llmCall.candidates_generated}
              </div>
            </div>
            <div>
              <div className="flex items-center gap-1.5 mb-2">
                <CheckCircle className="h-4 w-4 text-green-600 dark:text-green-400" />
                <span className="text-sm font-medium text-gray-600 dark:text-gray-400">
                  Candidates Valid
                </span>
              </div>
              <div className="text-2xl font-bold text-green-600 dark:text-green-400">
                {llmCall.candidates_valid}
              </div>
            </div>
          </div>
          {llmCall.parsing_errors && (
            <div className="mt-6 p-4 bg-red-50 dark:bg-red-900/20 rounded-lg border border-red-200 dark:border-red-800">
              <div className="flex items-center gap-2 mb-3">
                <XCircle className="h-4 w-4 text-red-600 dark:text-red-400" />
                <div className="text-sm font-semibold text-red-800 dark:text-red-300">
                  Parsing Errors
                </div>
              </div>
              <pre className="bg-white dark:bg-gray-900 p-3 rounded-lg text-xs overflow-auto text-gray-900 dark:text-gray-100 border border-red-200 dark:border-red-800 font-mono">
                {JSON.stringify(llmCall.parsing_errors, null, 2)}
              </pre>
            </div>
          )}
        </div>
      )}

      {/* Prompts */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-8 border border-gray-200 dark:border-gray-700">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-2">
            <FileText className="h-5 w-5 text-gray-600 dark:text-gray-400" />
            <h2 className="text-xl font-semibold text-gray-900 dark:text-white">System Prompt</h2>
            <InfoIcon
              content="Instructions that guide the model's behavior throughout the conversation"
              side="top"
            />
          </div>
          <div className="flex items-center gap-2">
            <span className="text-xs text-gray-500 dark:text-gray-400">
              {llmCall.system_prompt?.length.toLocaleString() || 0} characters
            </span>
            <CopyButton text={llmCall.system_prompt || ""} label="system prompt" size="sm" />
          </div>
        </div>
        <pre className="bg-gray-50 dark:bg-gray-900 p-4 rounded-lg text-sm overflow-auto whitespace-pre-wrap text-gray-900 dark:text-gray-100 leading-relaxed font-mono border border-gray-200 dark:border-gray-700">
          {llmCall.system_prompt}
        </pre>
      </div>

      <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-8 border border-gray-200 dark:border-gray-700">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-2">
            <FileText className="h-5 w-5 text-gray-600 dark:text-gray-400" />
            <h2 className="text-xl font-semibold text-gray-900 dark:text-white">User Prompt</h2>
            <InfoIcon
              content="Specific task and context for this call. Contains the code to optimize and requirements."
              side="top"
            />
          </div>
          <div className="flex items-center gap-2">
            <span className="text-xs text-gray-500 dark:text-gray-400">
              {llmCall.user_prompt?.length.toLocaleString() || 0} characters
            </span>
            <CopyButton text={llmCall.user_prompt || ""} label="user prompt" size="sm" />
          </div>
        </div>
        <pre className="bg-gray-50 dark:bg-gray-900 p-4 rounded-lg text-sm overflow-auto whitespace-pre-wrap text-gray-900 dark:text-gray-100 leading-relaxed font-mono border border-gray-200 dark:border-gray-700">
          {llmCall.user_prompt}
        </pre>
      </div>

      {/* Response — parsed by call type (ranking: rank/explain; optimization: code blocks + text), with View raw */}
      {llmCall.raw_response && (
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-8 border border-gray-200 dark:border-gray-700">
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center gap-2">
              <Code className="h-5 w-5 text-gray-600 dark:text-gray-400" />
              <h2 className="text-xl font-semibold text-gray-900 dark:text-white">LLM Response</h2>
              <InfoIcon
                content="Parsed view by call type: ranking shows order and explanation; optimization shows code blocks. Use View raw for the full string."
                side="top"
              />
            </div>
            <div className="flex items-center gap-2">
              <span className="text-xs text-gray-500 dark:text-gray-400">
                {llmCall.raw_response.length.toLocaleString()} characters
              </span>
              <CopyButton text={llmCall.raw_response} label="response" size="sm" />
            </div>
          </div>
          <ParsedResponseView rawResponse={llmCall.raw_response} callType={llmCall.call_type} />
        </div>
      )}

      {/* Error Information */}
      {llmCall.status === "failed" && llmCall.error_message && (
        <div className="bg-red-50 dark:bg-red-900/20 rounded-lg shadow p-6 mb-8 border-l-4 border-red-500 dark:border-red-600">
          <div className="flex items-start gap-3 mb-4">
            <XCircle className="h-6 w-6 text-red-600 dark:text-red-400 mt-0.5 flex-shrink-0" />
            <h2 className="text-xl font-semibold text-red-800 dark:text-red-400">
              Error Information
            </h2>
          </div>
          <div className="mb-4">
            <div className="flex items-center gap-2 mb-2">
              <span className="text-sm font-medium text-gray-700 dark:text-gray-300">
                Error Type:
              </span>
              <span className="px-2 py-1 bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-300 rounded text-sm font-semibold">
                {llmCall.error_type}
              </span>
            </div>
          </div>
          <div>
            <div className="flex items-center justify-between mb-2">
              <span className="text-sm font-medium text-gray-700 dark:text-gray-300">
                Error Message:
              </span>
              <CopyButton text={llmCall.error_message} label="error message" size="sm" />
            </div>
            <pre className="bg-white dark:bg-gray-900 p-3 rounded-lg text-sm overflow-auto text-red-700 dark:text-red-400 border border-red-200 dark:border-red-800 font-mono leading-relaxed">
              {llmCall.error_message}
            </pre>
          </div>
        </div>
      )}

      {/* Related Errors */}
      {relatedErrors.length > 0 && (
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-8 border border-gray-200 dark:border-gray-700">
          <div className="flex items-center gap-3 mb-4">
            <AlertTriangle className="h-5 w-5 text-orange-600 dark:text-orange-400" />
            <h2 className="text-xl font-semibold text-gray-900 dark:text-white">Related Errors</h2>
            <span className="bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-200 text-sm px-2.5 py-0.5 rounded font-semibold">
              {relatedErrors.length}
            </span>
          </div>
          <div className="space-y-4">
            {(
              relatedErrors as Array<{
                id: string
                error_type: string | null
                severity: string | null
                error_message: string | null
                context: unknown
                created_at: Date
              }>
            ).map(error => (
              <div
                key={error.id}
                className="border-l-4 border-red-500 dark:border-red-600 pl-4 py-2 bg-gray-50 dark:bg-gray-900/50 rounded-r-lg"
              >
                <div className="flex items-center gap-2 mb-2">
                  <span
                    className={`px-2 py-1 rounded text-xs font-semibold ${
                      error.severity === "critical"
                        ? "bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-200"
                        : error.severity === "error"
                          ? "bg-orange-100 dark:bg-orange-900 text-orange-800 dark:text-orange-200"
                          : "bg-yellow-100 dark:bg-yellow-900 text-yellow-800 dark:text-yellow-200"
                    }`}
                  >
                    {error.severity}
                  </span>
                  <span className="text-sm font-medium text-gray-700 dark:text-gray-300">
                    {error.error_type}
                  </span>
                  <span className="text-xs text-gray-500 dark:text-gray-400 ml-auto">
                    {new Date(error.created_at).toLocaleString()}
                  </span>
                </div>
                <div className="text-sm mb-2 text-gray-900 dark:text-gray-100 font-medium">
                  {error.error_message}
                </div>
                {error.context != null && (
                  <details className="text-sm text-gray-600 dark:text-gray-400">
                    <summary className="cursor-pointer hover:text-blue-600 dark:hover:text-blue-400">
                      View context
                    </summary>
                    <pre className="bg-white dark:bg-gray-900 p-3 rounded-lg mt-2 overflow-auto text-gray-900 dark:text-gray-100 text-xs border border-gray-200 dark:border-gray-700 font-mono">
                      {JSON.stringify(error.context as Record<string, unknown>, null, 2)}
                    </pre>
                  </details>
                )}
              </div>
            ))}
          </div>
        </div>
      )}
      {/* Actions */}
      <div className="flex flex-wrap gap-4">
        <Link
          href={`/observability/trace/${llmCall.trace_id}`}
          className="inline-flex items-center px-6 py-3 bg-blue-600 dark:bg-blue-700 text-white rounded-lg hover:bg-blue-700 dark:hover:bg-blue-600 transition-colors font-medium shadow-sm"
        >
          View Full Trace →
        </Link>
        <Link
          href="/observability/llm-calls"
          className="inline-flex items-center px-6 py-3 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 text-gray-900 dark:text-gray-100 transition-colors font-medium"
        >
          ← Back to List
        </Link>
      </div>
    </div>
  )
}
