'use client'

import { useEffect, useRef, useState, useCallback } from 'react'
import { createPortal } from 'react-dom'
import { cn } from '@/lib/utils'
import { ArrowsOut, X } from '@phosphor-icons/react'

interface MermaidProps {
  children: string
  className?: string
}

// Helper to detect dark mode
function useIsDarkMode() {
  const [isDark, setIsDark] = useState(false)
  
  useEffect(() => {
    const checkDarkMode = () => {
      setIsDark(document.documentElement.classList.contains('dark'))
    }
    
    checkDarkMode()
    
    // Watch for theme changes
    const observer = new MutationObserver(checkDarkMode)
    observer.observe(document.documentElement, { 
      attributes: true, 
      attributeFilter: ['class'] 
    })
    
    return () => observer.disconnect()
  }, [])
  
  return isDark
}

export function Mermaid({ children, className }: MermaidProps) {
  const contentRef = useRef<HTMLDivElement>(null)
  const [isLoaded, setIsLoaded] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [mounted, setMounted] = useState(false)
  const [modalSvg, setModalSvg] = useState<string>('')
  const [modalLoading, setModalLoading] = useState(false)
  const isDarkMode = useIsDarkMode()

  const code = typeof children === 'string' ? children.trim() : ''

  // Track if component is mounted (for portal)
  useEffect(() => {
    setMounted(true)
  }, [])

  // Render inline diagram
  useEffect(() => {
    if (!code || !contentRef.current) return

    const renderDiagram = async () => {
      try {
        const mermaid = (await import('mermaid')).default
        
        mermaid.initialize({
          startOnLoad: false,
          theme: isDarkMode ? 'dark' : 'default',
          securityLevel: 'loose',
          fontFamily: 'inherit',
        })

        const id = `mermaid-inline-${Math.random().toString(36).substr(2, 9)}`
        const { svg } = await mermaid.render(id, code)
        
        if (contentRef.current) {
          contentRef.current.innerHTML = svg
          setIsLoaded(true)
          setError(null)
        }
      } catch (err) {
        console.error('Mermaid rendering error:', err)
        setError(err instanceof Error ? err.message : 'Failed to render diagram')
        setIsLoaded(true)
      }
    }

    renderDiagram()
  }, [code, isDarkMode])

  // Render modal diagram when modal opens
  useEffect(() => {
    if (!isModalOpen || !code) return

    setModalLoading(true)
    setModalSvg('')

    const renderModalDiagram = async () => {
      try {
        const mermaid = (await import('mermaid')).default
        
        mermaid.initialize({
          startOnLoad: false,
          theme: isDarkMode ? 'dark' : 'default',
          securityLevel: 'loose',
          fontFamily: 'inherit',
        })

        const id = `mermaid-modal-${Math.random().toString(36).substr(2, 9)}`
        const { svg } = await mermaid.render(id, code)
        
        setModalSvg(svg)
        setModalLoading(false)
      } catch (err) {
        console.error('Mermaid modal rendering error:', err)
        setModalSvg(`<div class="p-4 text-red-500">Failed to render diagram</div>`)
        setModalLoading(false)
      }
    }

    renderModalDiagram()
  }, [isModalOpen, code, isDarkMode])

  // Close modal on escape key
  useEffect(() => {
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && isModalOpen) {
        setIsModalOpen(false)
      }
    }

    document.addEventListener('keydown', handleEscape)
    return () => document.removeEventListener('keydown', handleEscape)
  }, [isModalOpen])

  // Prevent body scroll when modal is open
  useEffect(() => {
    if (isModalOpen) {
      document.body.style.overflow = 'hidden'
    } else {
      document.body.style.overflow = ''
    }
    return () => {
      document.body.style.overflow = ''
    }
  }, [isModalOpen])

  const openModal = useCallback(() => {
    setIsModalOpen(true)
  }, [])

  const closeModal = useCallback(() => {
    setIsModalOpen(false)
  }, [])

  if (error) {
    return (
      <div className={cn(
        'my-4 p-4 rounded-lg border border-red-200 bg-red-50 dark:border-red-800 dark:bg-red-950',
        className
      )}>
        <p className="text-sm text-red-600 dark:text-red-400 font-medium">
          Failed to render Mermaid diagram
        </p>
        <pre className="mt-2 text-xs text-red-500 dark:text-red-400 overflow-auto">
          {error}
        </pre>
      </div>
    )
  }

  return (
    <>
      <div 
        className={cn(
          'my-4 relative rounded-lg border border-border bg-muted/30 overflow-hidden group',
          className
        )}
      >
        {/* Inline diagram */}
        <div className="overflow-hidden min-h-[200px] relative">
          <div
            ref={contentRef}
            className={cn(
              'flex items-center justify-center p-4',
              !isLoaded && 'opacity-0'
            )}
          />
          {!isLoaded && (
            <div className="absolute inset-0 flex items-center justify-center">
              <div className="text-sm text-muted-foreground">Loading diagram...</div>
            </div>
          )}
        </div>

        {/* Fullscreen button */}
        {isLoaded && (
          <button
            onClick={openModal}
            className="absolute bottom-3 right-3 p-2 bg-background/90 backdrop-blur-sm rounded-lg border border-border shadow-sm hover:bg-muted transition-colors opacity-0 group-hover:opacity-100"
            title="View fullscreen"
          >
            <ArrowsOut className="h-4 w-4" weight="bold" />
          </button>
        )}
      </div>

      {/* Modal via Portal */}
      {mounted && isModalOpen && createPortal(
        <div 
          className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/80 backdrop-blur-sm"
          onClick={closeModal}
        >
          <div 
            className="relative bg-background rounded-lg border border-border shadow-2xl w-[95vw] h-[95vh] overflow-auto flex items-center justify-center"
            onClick={(e) => e.stopPropagation()}
          >
            {/* Close button */}
            <button
              onClick={closeModal}
              className="absolute top-4 right-4 p-2 bg-muted/80 hover:bg-muted rounded-lg transition-colors z-10"
              title="Close (Esc)"
            >
              <X className="h-5 w-5" weight="bold" />
            </button>
            
            {/* Modal diagram */}
            {modalLoading ? (
              <div className="text-sm text-muted-foreground">Loading diagram...</div>
            ) : modalSvg ? (
              <div 
                className="p-8 flex items-center justify-center [&_svg]:w-auto [&_svg]:h-auto [&_svg]:min-w-[60vw] [&_svg]:min-h-[60vh] [&_svg]:max-w-[90vw] [&_svg]:max-h-[90vh]"
                dangerouslySetInnerHTML={{ __html: modalSvg }}
              />
            ) : (
              <div className="text-sm text-muted-foreground">No diagram content (modalSvg is empty)</div>
            )}
          </div>
        </div>,
        document.body
      )}
    </>
  )
}
