'use client'

import { useEffect, useState, useCallback, useRef } from 'react'
import { Spinner } from '@phosphor-icons/react'
import { MDXRemote, MDXRemoteSerializeResult } from 'next-mdx-remote'
import { useDocsNavigation } from '@/lib/docs-navigation-context'
import { useCodeCopy } from '@/hooks/use-code-copy'
import { NotFoundPage } from './not-found-page'

// Custom Link component for MDX - uses docs navigation context
function MdxLink({ href, children, ...props }: React.AnchorHTMLAttributes<HTMLAnchorElement>) {
  const docsNav = useDocsNavigation()
  
  const handleClick = useCallback((e: React.MouseEvent<HTMLAnchorElement>) => {
    // Handle anchor links (same page)
    if (href?.startsWith('#')) {
      return // Let default behavior handle anchor scrolling
    }
    
    // Handle internal doc links
    if (href?.startsWith('/') && docsNav?.isApiDocsView) {
      e.preventDefault()
      
      // Extract the slug from the path
      let slug = href
      
      // Remove leading slash
      if (slug.startsWith('/')) {
        slug = slug.slice(1)
      }
      
      // Handle special paths
      if (slug.startsWith('api-reference')) {
        docsNav.switchToTab('api-reference')
        return
      }
      
      if (slug.startsWith('changelog')) {
        docsNav.switchToTab('changelog')
        return
      }
      
      // Remove docs/ prefix if present
      if (slug.startsWith('docs/')) {
        slug = slug.slice(5)
      }
      
      // Navigate to the page
      docsNav.navigateToPage(slug)
    }
  }, [href, docsNav])
  
  // Determine link styling - better visibility and accessibility
  // Using visited: to override browser's purple visited link color
  const linkClassName = "text-primary visited:text-primary font-medium underline decoration-primary/30 underline-offset-2 hover:decoration-primary transition-colors"
  
  // External links
  if (href && !href.startsWith('/') && !href.startsWith('#')) {
    return (
      <a 
        href={href} 
        target="_blank" 
        rel="noopener noreferrer"
        className={linkClassName}
        {...props}
      >
        {children}
      </a>
    )
  }
  
  return (
    <a 
      href={href} 
      onClick={handleClick}
      className={linkClassName}
      {...props}
    >
      {children}
    </a>
  )
}

// Import MDX components
import {
  Note,
  Warning,
  Info,
  Tip,
  Check,
  Error as ErrorCallout,
  Callout,
  Card,
  CardGroup,
  Accordion,
  AccordionGroup,
  Steps,
  Step,
  Tabs,
  Tab,
  CodeGroup,
  Frame,
  Columns,
  Snippet,
  Latex,
  ParamField,
  ResponseField,
  Expandable,
  Iframe,
  Video,
  Loom,
  Image,
  Screenshot,
  Logo,
  Icon,
  Highlight,
  Marker,
  Underline,
  Badge,
  Mermaid,
  PDF,
  Audio,
  Download,
  // Landing Page Components
  Hero,
  Pre,
  Tagline,
  Headline,
  Description,
  CommandBox,
  Section,
  Center,
  FeatureGrid,
  FeatureItem,
  ButtonLink,
  Spacer,
  Divider,
} from '../../docs/mdx/index'

// MDX components mapping
const mdxComponents = {
  // Callouts
  Note,
  Warning,
  Info,
  Tip,
  Check,
  Error: ErrorCallout,
  Callout,
  
  // Cards
  Card,
  CardGroup,
  
  // Accordion
  Accordion,
  AccordionGroup,
  
  // Steps
  Steps,
  Step,
  
  // Tabs
  Tabs,
  Tab,
  
  // Code
  CodeGroup,
  
  // Layout
  Frame,
  Columns,
  Snippet,
  Latex,
  
  // API docs
  ParamField,
  ResponseField,
  Expandable,
  
  // Embeds
  Iframe,
  Video,
  Loom,
  
  // Images
  Image,
  Screenshot,
  Logo,
  Icon,
  
  // Highlight
  Highlight,
  Marker,
  Underline,
  
  // Badge
  Badge,
  
  // Mermaid
  Mermaid,
  
  // File Embeds
  PDF,
  Audio,
  Download,
  
  // Landing Page
  Hero,
  Pre,
  Tagline,
  Headline,
  Description,
  CommandBox,
  Section,
  Center,
  FeatureGrid,
  FeatureItem,
  ButtonLink,
  Spacer,
  Divider,
  
  // Links
  a: MdxLink,
}

interface DocPageProps {
  slug: string
  onSearch?: () => void
}

interface DocPageData {
  slug: string
  frontmatter: {
    title: string
    description?: string
    icon?: string
    // Page mode and layout options
    mode?: 'default' | 'wide' | 'custom'
    hideHeader?: boolean
    fullWidth?: boolean
    background?: string
  }
  mdxSource: MDXRemoteSerializeResult
}

export function DocPage({ slug, onSearch }: DocPageProps) {
  const [pageData, setPageData] = useState<DocPageData | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [isNotFound, setIsNotFound] = useState(false)
  const contentRef = useRef<HTMLDivElement>(null)
  
  // Add copy buttons to code blocks after content loads
  useCodeCopy(contentRef, [pageData])
  
  useEffect(() => {
    async function fetchPage() {
      try {
        setLoading(true)
        setError(null)
        setIsNotFound(false)
        
        const response = await fetch(`/api/docs?slug=${encodeURIComponent(slug)}`)
        
        if (response.status === 404) {
          setIsNotFound(true)
          return
        }
        
        if (!response.ok) {
          throw new Error('Failed to load page')
        }
        
        const data = await response.json()
        setPageData(data)
      } catch (err) {
        console.error('Error loading doc page:', err)
        setError(err instanceof Error ? err.message : 'Failed to load page')
      } finally {
        setLoading(false)
      }
    }
    
    fetchPage()
  }, [slug])
  
  if (loading) {
    return (
      <div className="docs-page docs-page-loading w-full min-h-[200px]">
        <div className="docs-loading flex items-center justify-center py-12">
          <Spinner className="h-6 w-6 animate-spin text-muted-foreground" />
        </div>
      </div>
    )
  }
  
  // Show 404 page for not found errors
  if (isNotFound) {
    return <NotFoundPage slug={slug} onSearch={onSearch} />
  }
  
  // Show generic error for other errors
  if (error || !pageData) {
    return (
      <div className="docs-page docs-page-error w-full min-h-[200px]">
        <div className="docs-error text-center py-12">
          <p className="text-destructive">{error || 'Failed to load page'}</p>
        </div>
      </div>
    )
  }
  
  const { mode = 'default', hideHeader, fullWidth, background } = pageData.frontmatter
  const isCustomMode = mode === 'custom'
  const isWideMode = mode === 'wide'
  const showHeader = !hideHeader && !isCustomMode
  
  // Custom mode: Full-width layout for landing pages
  if (isCustomMode) {
    return (
      <div 
        ref={contentRef} 
        className="docs-page docs-page-custom docs-content w-full min-h-full"
        style={{ 
          background: background || 'var(--background)',
          // Ensure the content fills the entire viewport width within the content area
          marginLeft: 0,
          marginRight: 0,
        }}
      >
        {/* Custom pages render MDX content directly without container constraints */}
        <div className="docs-custom-content [&>*]:w-full">
          <MDXRemote {...pageData.mdxSource} components={mdxComponents} />
        </div>
      </div>
    )
  }
  
  // Default/Wide mode: Standard documentation layout
  const containerClass = isWideMode 
    ? 'max-w-6xl' // Wide mode
    : 'max-w-4xl' // Default mode
  
  return (
    <div ref={contentRef} className={`docs-page docs-content ${containerClass} mx-auto px-4 py-6 sm:px-8 sm:py-8`}>
      {/* Page header - shown unless hideHeader is true */}
      {showHeader && (
        <div className="docs-page-header mb-6">
          <h1 className="docs-content-title text-2xl sm:text-3xl font-bold mb-2 text-foreground">
            {pageData.frontmatter.title}
          </h1>
          {pageData.frontmatter.description && (
            <p className="docs-content-description text-lg text-muted-foreground">
              {pageData.frontmatter.description}
            </p>
          )}
        </div>
      )}
      
      {/* Page content - MDX rendered with custom components */}
      <div className="docs-prose prose prose-sm max-w-none prose-headings:text-foreground prose-p:text-muted-foreground prose-strong:text-foreground prose-code:text-foreground prose-pre:bg-muted prose-code:bg-muted prose-code:px-1 prose-code:py-0.5 prose-code:rounded prose-pre:overflow-x-auto prose-table:w-full prose-th:text-left prose-th:p-3 prose-th:bg-muted prose-td:p-3 prose-td:border-b prose-td:border-border">
        <MDXRemote {...pageData.mdxSource} components={mdxComponents} />
      </div>
    </div>
  )
}
