'use client'

import ReactMarkdown from 'react-markdown'
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'
import { oneDark, oneLight } from 'react-syntax-highlighter/dist/esm/styles/prism'
import remarkGfm from 'remark-gfm'
import React, { useState } from 'react'
import { Copy, Check } from 'lucide-react'
import { cn } from '../../utils/cn'

/**
 * Themed markdown renderer for blog/article content.
 *
 * Uses shared design tokens (`text-foreground`, `border-border`, `bg-muted`,
 * `text-primary`, …) so it adopts each app's theme automatically. Decoupled from
 * `next-themes`: pass `theme="dark"` to switch the code-block syntax style (apps
 * using next-themes can forward `useTheme().resolvedTheme`).
 */
export interface MarkdownRendererProps {
  content: string
  /** Syntax-highlighting style for fenced code blocks. Default `"light"`. */
  theme?: 'light' | 'dark'
  className?: string
}

function slugify(text: string): string {
  return text
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/(^-|-$)/g, '')
}

export function MarkdownRenderer({ content, theme = 'light', className }: MarkdownRendererProps) {
  const [copiedCode, setCopiedCode] = useState<string | null>(null)

  const copyToClipboard = async (code: string) => {
    await navigator.clipboard.writeText(code)
    setCopiedCode(code)
    setTimeout(() => setCopiedCode(null), 2000)
  }

  return (
    <div className={cn('prose prose-lg max-w-none', className)}>
      <ReactMarkdown
        remarkPlugins={[remarkGfm]}
        components={{
          // h1 in content renders as h2 — the page template owns the real <h1>.
          h1: ({ children, ...props }) => (
            <h2 id={slugify(String(children ?? ''))} className="text-3xl font-heading font-semibold mb-4 mt-10 first:mt-0 text-foreground scroll-mt-8" {...props}>
              {children}
            </h2>
          ),
          h2: ({ children, ...props }) => (
            <h2 id={slugify(String(children ?? ''))} className="text-3xl font-heading font-semibold mb-4 mt-10 first:mt-0 text-foreground scroll-mt-8" {...props}>
              {children}
            </h2>
          ),
          h3: ({ children, ...props }) => (
            <h3 id={slugify(String(children ?? ''))} className="text-2xl font-heading font-semibold mb-3 mt-8 first:mt-0 text-foreground scroll-mt-8" {...props}>
              {children}
            </h3>
          ),
          h4: ({ children, ...props }) => (
            <h4 id={slugify(String(children ?? ''))} className="text-xl font-heading font-semibold mb-2 mt-6 first:mt-0 text-foreground scroll-mt-8" {...props}>
              {children}
            </h4>
          ),
          a: ({ children, ...props }) => (
            <a className="text-primary underline underline-offset-2 hover:opacity-80 transition-opacity" {...props}>
              {children}
            </a>
          ),
          code: (codeProps) => {
            const { className: codeClassName, children, ...props } = codeProps as {
              className?: string
              children?: React.ReactNode
            }
            const match = /language-(\w+)/.exec(codeClassName || '')
            const language = match ? match[1] : ''
            const codeString = String(children).replace(/\n$/, '')

            if (language) {
              const syntaxStyle = theme === 'dark' ? oneDark : oneLight
              return (
                <div className="my-6 rounded-lg overflow-hidden border border-border shadow-sm">
                  <div className="flex items-center justify-between bg-muted px-4 py-2 border-b border-border">
                    <span className="text-sm font-medium text-muted-foreground">{language}</span>
                    <button
                      onClick={() => copyToClipboard(codeString)}
                      className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors p-1 rounded"
                      title="Copy code"
                      aria-label={copiedCode === codeString ? 'Code copied' : 'Copy code to clipboard'}
                    >
                      {copiedCode === codeString ? <Check className="h-3 w-3" /> : <Copy className="h-3 w-3" />}
                    </button>
                  </div>
                  <SyntaxHighlighter
                    style={syntaxStyle as Record<string, React.CSSProperties>}
                    language={language}
                    PreTag="div"
                    customStyle={{ margin: 0, padding: '1rem', background: 'transparent', fontSize: '0.875rem', lineHeight: '1.5' }}
                    codeTagProps={{
                      style: {
                        background: 'transparent',
                        fontFamily:
                          "ui-monospace, SFMono-Regular, 'SF Mono', Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace",
                      },
                    }}
                  >
                    {codeString}
                  </SyntaxHighlighter>
                </div>
              )
            }

            return (
              <code className="bg-muted px-2 py-1 rounded text-sm font-mono text-foreground border border-border" {...props}>
                {children}
              </code>
            )
          },
          table: ({ children, ...props }) => (
            <div className="overflow-x-auto my-8">
              <table className="w-full border-collapse bg-card rounded-lg border border-border shadow-sm" {...props}>
                {children}
              </table>
            </div>
          ),
          thead: ({ children, ...props }) => (
            <thead className="bg-muted" {...props}>
              {children}
            </thead>
          ),
          th: ({ children, ...props }) => (
            <th className="px-4 py-3 text-left font-semibold border-b border-border text-foreground" {...props}>
              {children}
            </th>
          ),
          td: ({ children, ...props }) => (
            <td className="px-4 py-3 border-b border-border text-foreground" {...props}>
              {children}
            </td>
          ),
          tr: ({ children, ...props }) => (
            <tr className="hover:bg-muted/50" {...props}>
              {children}
            </tr>
          ),
          p: ({ children, ...props }) => (
            <p className="mb-6 leading-relaxed text-foreground" {...props}>
              {children}
            </p>
          ),
          strong: ({ children, ...props }) => (
            <strong className="font-semibold text-foreground" {...props}>
              {children}
            </strong>
          ),
          em: ({ children, ...props }) => (
            <em className="italic text-foreground" {...props}>
              {children}
            </em>
          ),
          ul: ({ children, ...props }) => (
            <ul className="mb-6 space-y-2 list-disc ml-6" {...props}>
              {children}
            </ul>
          ),
          ol: ({ children, ...props }) => (
            <ol className="mb-6 space-y-2 list-decimal ml-6" {...props}>
              {children}
            </ol>
          ),
          li: ({ children, ...props }) => (
            <li className="text-foreground leading-relaxed" {...props}>
              {children}
            </li>
          ),
          hr: ({ ...props }) => <hr className="my-8 border-border" {...props} />,
          blockquote: ({ children, ...props }) => (
            <blockquote className="my-6 pl-6 border-l-4 border-primary bg-muted py-4 pr-4 rounded-r-lg" {...props}>
              <div className="text-muted-foreground italic">{children}</div>
            </blockquote>
          ),
        }}
      >
        {content}
      </ReactMarkdown>
    </div>
  )
}
