'use client'

import { useEffect, useState } from 'react'
import { Spinner } from '@phosphor-icons/react'
import { MDXRemote, MDXRemoteSerializeResult } from 'next-mdx-remote'
import { cn } from '@/lib/utils'

// Import base MDX components (using relative path for Vercel compatibility)
import {
  Note,
  Warning as WarningCallout,
  Info,
  Tip,
  Check,
  Error as ErrorCallout,
  Callout,
} from '../../docs/mdx/index'

interface ChangelogRelease {
  version: string
  date: string
  title: string
  slug: string
}

interface ChangelogPageProps {
  releases: ChangelogRelease[]
  selectedVersion?: string | null
  onSelectVersion?: (version: string) => void
  tabName?: string  // Tab name from config (e.g., "Changelog", "Releases")
}

interface ReleaseContent {
  frontmatter: {
    title: string
    version: string
    date: string
  }
  mdxSource: MDXRemoteSerializeResult
}

// Custom styled components for changelog content
const changelogMdxComponents = {
  h2: ({ children, ...props }: { children: React.ReactNode }) => (
    <h2 className="text-lg font-semibold text-foreground mt-6 mb-3" {...props}>{children}</h2>
  ),
  h3: ({ children, ...props }: { children: React.ReactNode }) => (
    <h3 className="text-base font-medium text-foreground mt-4 mb-2" {...props}>{children}</h3>
  ),
  p: ({ children, ...props }: { children: React.ReactNode }) => (
    <p className="text-muted-foreground mb-4" {...props}>{children}</p>
  ),
  ul: ({ children, ...props }: { children: React.ReactNode }) => (
    <ul className="space-y-2 text-muted-foreground mb-4" {...props}>{children}</ul>
  ),
  li: ({ children, ...props }: { children: React.ReactNode }) => (
    <li className="flex items-start gap-2" {...props}>
      <span className="mt-2 h-1.5 w-1.5 rounded-full bg-foreground shrink-0" />
      <span>{children}</span>
    </li>
  ),
  strong: ({ children, ...props }: { children: React.ReactNode }) => (
    <strong className="font-semibold text-foreground" {...props}>{children}</strong>
  ),
  // Keep callout components
  Note,
  Warning: WarningCallout,
  Info,
  Tip,
  Check,
  Error: ErrorCallout,
  Callout,
}

// Format date to be more readable
function formatDate(dateString: string): string {
  try {
    const date = new Date(dateString)
    return date.toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    })
  } catch {
    return dateString
  }
}

// Extract version from slug (e.g., "changelog/v1.2.0" -> "v1.2.0")
function getVersionFromSlug(slug: string): string {
  return slug.replace(/^changelog\//, '')
}

// Single release entry component
function ReleaseEntry({ 
  release, 
  content, 
  isLatest,
  isLast,
}: { 
  release: ChangelogRelease
  content: ReleaseContent | null
  isLatest: boolean
  isLast: boolean
}) {
  // Use version extracted from slug for the ID (without changelog/ prefix)
  const versionId = getVersionFromSlug(release.slug)
  
  return (
    <article 
      id={`release-${versionId}`}
      className="docs-changelog-entry relative scroll-mt-24 pl-8"
    >
      {/* Timeline line - extends full height except for last item */}
      {!isLast && (
        <div className="absolute left-[3px] top-3 bottom-0 w-[2px] bg-border" />
      )}
      
      {/* Timeline dot */}
      <div className={cn(
        "absolute left-0 top-[6px] w-[8px] h-[8px] rounded-full border-2 z-10",
        isLatest 
          ? "bg-primary border-primary" 
          : "bg-background border-muted-foreground/40"
      )} />

      <div className="pb-10">
        {/* Version badge and date header */}
        <div className="flex flex-wrap items-center gap-3 mb-4">
          <span className={cn(
            "docs-changelog-version inline-flex items-center px-3 py-1 text-sm font-semibold rounded-full",
            isLatest 
              ? "bg-primary/10 text-primary border border-primary/20" 
              : "bg-muted text-foreground border border-border"
          )}>
            {release.version}
            {isLatest && (
              <span className="ml-2 text-xs font-normal opacity-75">Latest</span>
            )}
          </span>
          <time className="docs-changelog-date text-sm text-muted-foreground">
            {formatDate(release.date)}
          </time>
        </div>

        {/* Release title */}
        <h2 className="docs-changelog-title text-xl font-semibold text-foreground mb-4">
          {release.title}
        </h2>

        {/* Release content */}
        {content ? (
          <div className="docs-changelog-content prose prose-sm dark:prose-invert max-w-none">
            <MDXRemote {...content.mdxSource} components={changelogMdxComponents} />
          </div>
        ) : (
          <div className="flex items-center gap-2 text-muted-foreground py-4">
            <Spinner className="h-4 w-4 animate-spin" />
            <span className="text-sm">Loading...</span>
          </div>
        )}
      </div>
    </article>
  )
}

export function ChangelogPage({ releases, tabName = 'Changelog' }: ChangelogPageProps) {
  const [releaseContents, setReleaseContents] = useState<Map<string, ReleaseContent>>(new Map())
  const [loadingAll, setLoadingAll] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [activeVersion, setActiveVersion] = useState<string | null>(releases[0]?.version || null)

  // Load all releases on mount
  useEffect(() => {
    async function fetchAllReleases() {
      if (releases.length === 0) {
        setLoadingAll(false)
        return
      }

      setLoadingAll(true)
      setError(null)

      const contents = new Map<string, ReleaseContent>()

      // Fetch all releases in parallel
      const fetchPromises = releases.map(async (release) => {
        try {
          const response = await fetch(`/api/docs?slug=${encodeURIComponent(release.slug)}`)
          if (response.ok) {
            const data = await response.json()
            contents.set(release.version, data)
          }
        } catch (err) {
          console.error(`Error loading release ${release.version}:`, err)
        }
      })

      await Promise.all(fetchPromises)
      setReleaseContents(contents)
      setLoadingAll(false)
    }

    fetchAllReleases()
  }, [releases])

  // Track active version based on scroll position
  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        for (const entry of entries) {
          if (entry.isIntersecting) {
            const version = entry.target.getAttribute('data-version')
            if (version) {
              setActiveVersion(version)
            }
          }
        }
      },
      { rootMargin: '-100px 0px -70% 0px', threshold: 0 }
    )

    // Observe all release entries
    releases.forEach((release) => {
      const versionId = getVersionFromSlug(release.slug)
      const element = document.getElementById(`release-${versionId}`)
      if (element) {
        element.setAttribute('data-version', release.version)
        observer.observe(element)
      }
    })

    return () => observer.disconnect()
  }, [releases, releaseContents])

  const scrollToRelease = (slug: string) => {
    const versionId = getVersionFromSlug(slug)
    const element = document.getElementById(`release-${versionId}`)
    if (element) {
      element.scrollIntoView({ behavior: 'smooth', block: 'start' })
    }
  }

  if (releases.length === 0) {
    return (
      <div className="flex-1 flex items-center justify-center py-12">
        <p className="text-muted-foreground">No changelog releases found.</p>
      </div>
    )
  }

  return (
    <div className="docs-changelog flex flex-1 h-full overflow-hidden">
      {/* Main content area */}
      <div className="docs-changelog-main flex-1 overflow-y-auto">
        <div className="max-w-3xl mx-auto px-6 py-8 lg:px-8">
          {/* Header */}
          <header className="docs-changelog-header mb-10">
            <h1 className="docs-content-title text-3xl font-bold text-foreground mb-2">
              {tabName}
            </h1>
            <p className="text-muted-foreground">
              All notable changes and updates to this project.
            </p>
          </header>

          {/* Loading state */}
          {loadingAll && releaseContents.size === 0 && (
            <div className="docs-loading flex items-center justify-center py-12">
              <Spinner className="h-6 w-6 animate-spin text-muted-foreground" />
            </div>
          )}

          {/* Error state */}
          {error && (
            <div className="docs-error text-center py-12">
              <p className="text-destructive">{error}</p>
            </div>
          )}

          {/* Releases list with connected timeline */}
          <div className="docs-changelog-releases relative">
            {releases.map((release, index) => (
              <ReleaseEntry
                key={release.version}
                release={release}
                content={releaseContents.get(release.version) || null}
                isLatest={index === 0}
                isLast={index === releases.length - 1}
              />
            ))}
          </div>
        </div>
      </div>

      {/* Right sidebar - Version navigation */}
      {releases.length > 1 && (
        <aside className="docs-changelog-sidebar hidden lg:flex lg:flex-col w-48 h-full border-l border-border bg-muted/20 overflow-y-auto shrink-0">
          <div className="p-4 sticky top-0">
            <h3 className="docs-changelog-sidebar-title text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-3">
              Releases
            </h3>
            <nav className="docs-changelog-nav space-y-1">
              {releases.map((release, index) => (
                <button
                  key={release.version}
                  onClick={() => scrollToRelease(release.slug)}
                  className={cn(
                    'docs-changelog-nav-item block w-full text-left px-3 py-2 text-sm rounded-md transition-all duration-200',
                    activeVersion === release.version
                      ? 'docs-changelog-nav-item-active bg-primary/10 text-primary font-medium'
                      : 'text-muted-foreground hover:text-foreground hover:bg-muted'
                  )}
                >
                  <span className="flex items-center gap-2">
                    {release.version}
                    {index === 0 && (
                      <span className="text-[10px] px-1.5 py-0.5 rounded bg-primary/10 text-primary">
                        Latest
                      </span>
                    )}
                  </span>
                </button>
              ))}
            </nav>
          </div>
        </aside>
      )}
    </div>
  )
}
