"use client"

import {
  extractExplainTag,
  extractRankTag,
  getResponseContentForParsing,
  splitMarkdownCodeBlocks,
  type ResponseSegment,
} from "@/lib/observability-response-parse"
import { CopyButton } from "@/components/observability/copy-button"
import { SyntaxHighlighter } from "@/lib/syntax-highlighter"
import { oneDark } from "react-syntax-highlighter/dist/esm/styles/prism"
import { useState } from "react"

interface ParsedResponseViewProps {
  rawResponse: string
  callType: string | null
}

/** Try to parse JSON and return pretty-printed version, or null if not JSON */
function tryFormatJSON(content: string): string | null {
  try {
    const parsed = JSON.parse(content)
    return JSON.stringify(parsed, null, 2)
  } catch {
    return null
  }
}

export function ParsedResponseView({ rawResponse, callType }: ParsedResponseViewProps) {
  const [showRaw, setShowRaw] = useState(false)
  const isRanking = callType === "ranking"
  // Use inner message content when raw_response is API JSON (e.g. OpenAI)
  const contentForParsing = getResponseContentForParsing(rawResponse)
  const rankContent = isRanking ? extractRankTag(contentForParsing) : null
  const explainContent = isRanking ? extractExplainTag(contentForParsing) : null
  const hasRankingSections = isRanking && (rankContent != null || explainContent != null)

  const segments: ResponseSegment[] = hasRankingSections
    ? []
    : splitMarkdownCodeBlocks(contentForParsing)
  const hasSegments = segments.length > 0

  // Check if raw response is JSON (for fallback display)
  const formattedJSON = tryFormatJSON(rawResponse)
  const isJSON = formattedJSON != null

  return (
    <div className="space-y-4">
      {/* View raw toggle button - always visible in header */}
      <div className="flex items-center justify-end gap-2 pb-2 border-b border-gray-200 dark:border-gray-700">
        <button
          onClick={() => setShowRaw(!showRaw)}
          className="text-sm font-medium text-gray-600 dark:text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 flex items-center gap-1.5"
        >
          <span className={showRaw ? "rotate-90 transition-transform" : "transition-transform"}>
            ▶
          </span>
          {showRaw ? "Hide raw" : "View raw"}
        </button>
        <CopyButton text={rawResponse} label="raw response" size="sm" />
      </div>

      {showRaw && (
        <div className="rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden">
          <pre className="bg-gray-50 dark:bg-gray-900 p-4 text-sm overflow-auto whitespace-pre-wrap text-gray-900 dark:text-gray-100 font-mono max-h-96">
            {rawResponse}
          </pre>
        </div>
      )}

      {!showRaw && (
        <div className="space-y-4">
          {hasRankingSections && (
            <div className="space-y-4">
              {rankContent != null && (
                <div className="rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden">
                  <div className="px-4 py-2 bg-gray-100 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
                    <h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300">
                      Ranking (best first)
                    </h3>
                    <CopyButton text={rankContent} label="ranking" size="sm" />
                  </div>
                  <div className="p-4 bg-gray-50 dark:bg-gray-900">
                    <ol className="flex flex-wrap gap-2 list-none">
                      {rankContent
                        .split(/[\s,]+/)
                        .filter(Boolean)
                        .map((id, i) => {
                          const pos = i + 1
                          const label =
                            pos === 1 ? "1st" : pos === 2 ? "2nd" : pos === 3 ? "3rd" : `${pos}th`
                          return (
                            <li
                              key={`${id}-${i}`}
                              className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-600 text-sm font-mono"
                            >
                              <span className="text-gray-500 dark:text-gray-400 font-medium">
                                {label}
                              </span>
                              <span className="text-gray-900 dark:text-gray-100">{id.trim()}</span>
                            </li>
                          )
                        })}
                    </ol>
                  </div>
                </div>
              )}
              {explainContent != null && (
                <div className="rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden">
                  <div className="px-4 py-2 bg-gray-100 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700">
                    <h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300">
                      Explanation
                    </h3>
                  </div>
                  <div className="p-4 bg-gray-50 dark:bg-gray-900">
                    <div className="flex items-start gap-2">
                      <p className="flex-1 text-sm text-gray-700 dark:text-gray-300 whitespace-pre-wrap leading-relaxed">
                        {explainContent}
                      </p>
                      <CopyButton text={explainContent} label="explanation" size="sm" />
                    </div>
                  </div>
                </div>
              )}
            </div>
          )}

          {!hasRankingSections && hasSegments && (
            <div className="space-y-4">
              {segments.map((seg, i) => {
                const textJSON = seg.kind === "text" ? tryFormatJSON(seg.content) : null
                return seg.kind === "text" ? (
                  <div
                    key={i}
                    className="rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden"
                  >
                    {textJSON ? (
                      <SyntaxHighlighter
                        language="json"
                        style={oneDark}
                        PreTag="div"
                        customStyle={{
                          margin: 0,
                          padding: "1rem",
                          fontSize: "0.875rem",
                          lineHeight: 1.5,
                        }}
                        codeTagProps={{ className: "text-sm" }}
                        showLineNumbers={textJSON.split("\n").length > 10}
                      >
                        {textJSON}
                      </SyntaxHighlighter>
                    ) : (
                      <pre className="bg-gray-50 dark:bg-gray-900 p-4 text-sm overflow-auto whitespace-pre-wrap text-gray-900 dark:text-gray-100 font-mono">
                        {seg.content}
                      </pre>
                    )}
                  </div>
                ) : (
                  <div
                    key={i}
                    className="rounded-lg overflow-hidden border border-gray-200 dark:border-gray-700"
                  >
                    <div className="flex items-center justify-between px-3 py-1.5 bg-gray-100 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700">
                      <span className="text-xs font-medium text-gray-600 dark:text-gray-400">
                        {seg.language || "code"}
                      </span>
                      <CopyButton text={seg.content} label="code block" size="sm" />
                    </div>
                    <SyntaxHighlighter
                      language={seg.language === "text" ? "plaintext" : seg.language}
                      style={oneDark}
                      PreTag="div"
                      customStyle={{
                        margin: 0,
                        padding: "1rem",
                        fontSize: "0.875rem",
                        lineHeight: 1.5,
                      }}
                      codeTagProps={{ className: "text-sm" }}
                      showLineNumbers={seg.content.split("\n").length > 5}
                    >
                      {seg.content}
                    </SyntaxHighlighter>
                  </div>
                )
              })}
            </div>
          )}

          {!hasRankingSections && !hasSegments && (
            <div className="rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden">
              {isJSON ? (
                <SyntaxHighlighter
                  language="json"
                  style={oneDark}
                  PreTag="div"
                  customStyle={{
                    margin: 0,
                    padding: "1rem",
                    fontSize: "0.875rem",
                    lineHeight: 1.5,
                  }}
                  codeTagProps={{ className: "text-sm" }}
                  showLineNumbers={formattedJSON.split("\n").length > 10}
                >
                  {formattedJSON}
                </SyntaxHighlighter>
              ) : (
                <pre className="bg-gray-50 dark:bg-gray-900 p-4 text-sm overflow-auto whitespace-pre-wrap text-gray-900 dark:text-gray-100 font-mono max-h-96">
                  {rawResponse}
                </pre>
              )}
            </div>
          )}
        </div>
      )}
    </div>
  )
}
