'use client';

import React, { useMemo } from 'react';
import ReactMarkdown from 'react-markdown';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { oneDark } from 'react-syntax-highlighter/dist/esm/styles/prism';

interface MarkdownResponseProps {
  content: string;
  isThinkModel?: boolean;
  streaming?: boolean;
}

// F27: Split <think>...</think> blocks from the main response
function splitThinkBlocks(text: string): { thinking: string | null; answer: string } {
  const thinkMatch = text.match(/^<think>([\s\S]*?)<\/think>\s*/);
  if (thinkMatch) {
    return {
      thinking: thinkMatch[1].trim(),
      answer: text.slice(thinkMatch[0].length).trim(),
    };
  }
  // Partial think block (still streaming)
  if (text.startsWith('<think>') && !text.includes('</think>')) {
    return {
      thinking: text.slice(7).trim(),
      answer: '',
    };
  }
  return { thinking: null, answer: text };
}

export function MarkdownResponse({ content, isThinkModel, streaming }: MarkdownResponseProps) {
  const { thinking, answer } = useMemo(() => {
    if (!isThinkModel) return { thinking: null, answer: content };
    return splitThinkBlocks(content);
  }, [content, isThinkModel]);

  return (
    <div className="markdown-response">
      {/* F27: Collapsible think block */}
      {thinking && (
        <details className="mb-3" open={!answer && streaming}>
          <summary
            className="cursor-pointer text-[11px] font-medium px-2 py-1 rounded"
            style={{ color: 'var(--warning)', background: 'rgba(245, 158, 11, 0.08)' }}
          >
            Show reasoning ({thinking.split(/\s+/).length} words)
          </summary>
          <pre
            className="mt-1 p-3 rounded text-xs whitespace-pre-wrap overflow-auto max-h-40"
            style={{
              background: 'var(--bg-canvas)',
              color: 'var(--text-tertiary)',
              fontFamily: "'SF Mono', 'Fira Code', ui-monospace, monospace",
            }}
          >
            {thinking}
          </pre>
        </details>
      )}
      {/* F25/F26: Markdown with syntax highlighted code blocks */}
      <div className="prose-dark">
        <ReactMarkdown
          components={{
            code({ className, children, ...props }) {
              const match = /language-(\w+)/.exec(className || '');
              const codeString = String(children).replace(/\n$/, '');
              if (match) {
                return (
                  <div className="relative my-2">
                    <div
                      className="flex items-center justify-between px-3 py-1 rounded-t text-[10px] font-mono"
                      style={{ background: 'rgba(0,0,0,0.3)', color: 'var(--text-tertiary)' }}
                    >
                      <span>{match[1]}</span>
                    </div>
                    <SyntaxHighlighter
                      style={oneDark}
                      language={match[1]}
                      PreTag="div"
                      customStyle={{
                        margin: 0,
                        borderRadius: '0 0 0.375rem 0.375rem',
                        fontSize: '12px',
                        maxHeight: '300px',
                      }}
                    >
                      {codeString}
                    </SyntaxHighlighter>
                  </div>
                );
              }
              return (
                <code
                  className="px-1.5 py-0.5 rounded text-[12px] font-mono"
                  style={{ background: 'var(--surface-muted)', color: 'var(--accent-secondary)' }}
                  {...props}
                >
                  {children}
                </code>
              );
            },
            p({ children }) {
              return (
                <p
                  className="mb-2 last:mb-0"
                  style={{ color: 'var(--text-secondary)', lineHeight: '1.6' }}
                >
                  {children}
                </p>
              );
            },
            h1({ children }) {
              return (
                <h1
                  className="text-lg font-bold mt-3 mb-1"
                  style={{ color: 'var(--text-primary)' }}
                >
                  {children}
                </h1>
              );
            },
            h2({ children }) {
              return (
                <h2
                  className="text-base font-bold mt-3 mb-1"
                  style={{ color: 'var(--text-primary)' }}
                >
                  {children}
                </h2>
              );
            },
            h3({ children }) {
              return (
                <h3
                  className="text-sm font-bold mt-2 mb-1"
                  style={{ color: 'var(--text-primary)' }}
                >
                  {children}
                </h3>
              );
            },
            ul({ children }) {
              return (
                <ul
                  className="list-disc list-inside mb-2 space-y-0.5"
                  style={{ color: 'var(--text-secondary)' }}
                >
                  {children}
                </ul>
              );
            },
            ol({ children }) {
              return (
                <ol
                  className="list-decimal list-inside mb-2 space-y-0.5"
                  style={{ color: 'var(--text-secondary)' }}
                >
                  {children}
                </ol>
              );
            },
            li({ children }) {
              return <li className="text-sm">{children}</li>;
            },
            blockquote({ children }) {
              return (
                <blockquote
                  className="border-l-2 pl-3 my-2"
                  style={{ borderColor: 'var(--accent-primary)', color: 'var(--text-tertiary)' }}
                >
                  {children}
                </blockquote>
              );
            },
            strong({ children }) {
              return (
                <strong className="font-bold" style={{ color: 'var(--text-primary)' }}>
                  {children}
                </strong>
              );
            },
            em({ children }) {
              return <em style={{ color: 'var(--text-secondary)' }}>{children}</em>;
            },
            a({ href, children }) {
              return (
                <a
                  href={href}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="underline"
                  style={{ color: 'var(--accent-primary)' }}
                >
                  {children}
                </a>
              );
            },
          }}
        >
          {answer || (streaming ? '' : '(empty response)')}
        </ReactMarkdown>
      </div>
      {streaming && (
        <span
          className="inline-block w-2 h-4 ml-0.5 animate-pulse"
          style={{ background: 'var(--accent-primary)' }}
        />
      )}
    </div>
  );
}
