'use client'

import React from 'react'
import Link from 'next/link'
import { cn } from '@/lib/utils'
import { ArrowRight, ArrowSquareOut } from '@phosphor-icons/react'
import * as PhosphorIcons from '@phosphor-icons/react'
import { useDocsNavigation } from '@/lib/docs-navigation-context'

/**
 * Card Components for MDX Documentation
 * 
 * Mintlify-compatible card components for navigation and content organization.
 * Supports both ApiDocs hash-based navigation and standalone /docs route navigation.
 */

interface CardProps {
  title: string
  children?: React.ReactNode
  icon?: string | React.ReactNode  // Icon name (string) or custom React node
  iconSize?: 'sm' | 'md' | 'lg' | 'xl'  // Size of icon container: sm=32px, md=40px (default), lg=48px, xl=64px
  href?: string
  horizontal?: boolean
  img?: string  // Full-width header image
  cta?: string
  arrow?: boolean
  className?: string
}

// Dynamic icon resolver for Phosphor icons
function getIcon(iconName: string): React.ComponentType<{ className?: string; weight?: string }> | null {
  if (!iconName) return null
  
  // Convert kebab-case or snake_case to PascalCase
  const pascalCase = iconName
    .split(/[-_]/)
    .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
    .join('')
  
  // Try to get the icon from Phosphor
  const Icon = (PhosphorIcons as Record<string, unknown>)[pascalCase] as React.ComponentType<{ className?: string; weight?: string }> | undefined
  return Icon || null
}

// Icon size configurations
const ICON_SIZES = {
  sm: { container: 'h-8 w-8', icon: 'h-4 w-4', img: 'h-5 w-5' },
  md: { container: 'h-10 w-10', icon: 'h-5 w-5', img: 'h-6 w-6' },
  lg: { container: 'h-12 w-12', icon: 'h-6 w-6', img: 'h-8 w-8' },
  xl: { container: 'h-16 w-16', icon: 'h-8 w-8', img: 'h-12 w-12' },
}

export function Card({
  title,
  children,
  icon,
  iconSize = 'md',
  href,
  horizontal = false,
  img,
  cta,
  arrow,
  className,
}: CardProps) {
  // Check if icon is a string (icon name) or React node
  const isIconString = typeof icon === 'string'
  const Icon = isIconString ? getIcon(icon) : null
  const hasCustomIcon = !isIconString && icon != null
  const sizeConfig = ICON_SIZES[iconSize]
  const isExternal = href?.startsWith('http') || href?.startsWith('//')
  const docsNav = useDocsNavigation()
  
  // Check if this is a tab switch link (/api-reference, /changelog)
  const isTabSwitchLink = (href === '/api-reference' || href === '/changelog') && docsNav?.isApiDocsView
  
  // Check if this is an internal docs link (starts with / but not external or tab switch)
  const isInternalDocsLink = href?.startsWith('/') && !isExternal && !isTabSwitchLink && docsNav?.isApiDocsView
  
  // Extract slug from href - removes /docs/ prefix if present, or just the leading /
  const getSlugFromHref = (path: string): string => {
    let slug = path
    if (slug.startsWith('/docs/')) {
      slug = slug.slice(6) // Remove '/docs/'
    } else if (slug.startsWith('/')) {
      slug = slug.slice(1) // Remove leading '/'
    }
    return slug
  }
  
  // Get tab ID from href
  const getTabIdFromHref = (path: string): string => {
    if (path === '/api-reference') return 'api-reference'
    if (path === '/changelog') return 'changelog'
    return 'docs'
  }
  
  // Handle click for internal navigation
  const handleClick = (e: React.MouseEvent) => {
    if (!href || !docsNav) return
    
    if (isTabSwitchLink) {
      e.preventDefault()
      const tabId = getTabIdFromHref(href)
      docsNav.switchToTab(tabId)
    } else if (isInternalDocsLink) {
      e.preventDefault()
      const slug = getSlugFromHref(href)
      docsNav.navigateToPage(slug)
    }
  }
  const showArrow = arrow ?? isExternal
  
  const cardContent = (
    <div
      className={cn(
        'docs-card group relative rounded-lg border border-border bg-card p-4 transition-all h-full',
        href && 'hover:border-primary/50 hover:shadow-md cursor-pointer',
        horizontal ? 'docs-card-horizontal flex items-start gap-4' : 'flex flex-col justify-start',
        className
      )}
    >
      {/* Image */}
      {img && !horizontal && (
        <div className="mb-4 -mx-4 -mt-4 overflow-hidden rounded-t-lg">
          <img
            src={img}
            alt={title}
            className="w-full h-auto object-cover"
          />
        </div>
      )}
      
      {/* Icon (Phosphor icon from string) */}
      {Icon && (
        <div
          className={cn(
            'docs-card-icon flex shrink-0 items-center justify-center rounded-lg',
            sizeConfig.container,
            'bg-primary/10 text-primary',
            horizontal && 'mt-0.5'
          )}
        >
          <Icon className={sizeConfig.icon} weight="duotone" />
        </div>
      )}
      
      {/* Custom Icon (React node - image, svg, etc.) */}
      {hasCustomIcon && (
        <div
          className={cn(
            'docs-card-icon flex shrink-0 items-center justify-center rounded-lg overflow-hidden',
            sizeConfig.container,
            horizontal && 'mt-0.5'
          )}
        >
          {icon}
        </div>
      )}
      
      {/* Content */}
      <div className={cn('docs-card-content min-w-0', horizontal && 'flex-1', !horizontal && (Icon || hasCustomIcon) && 'mt-3')}>
        <div className="flex items-center gap-2">
          <h3 className="docs-card-title font-semibold text-foreground group-hover:text-primary transition-colors">
            {title}
          </h3>
          {showArrow && (
            isExternal ? (
              <ArrowSquareOut className="h-4 w-4 text-muted-foreground" />
            ) : (
              <ArrowRight className="h-4 w-4 text-muted-foreground opacity-0 -translate-x-2 group-hover:opacity-100 group-hover:translate-x-0 transition-all" />
            )
          )}
        </div>
        
        {children && (
          <div className="docs-card-description mt-1 text-sm text-muted-foreground">
            {children}
          </div>
        )}
        
        {cta && (
          <div className="docs-card-cta mt-3 text-sm font-medium text-primary">
            {cta}
          </div>
        )}
      </div>
    </div>
  )
  
  if (href) {
    if (isExternal) {
      return (
        <a href={href} target="_blank" rel="noopener noreferrer" className="docs-card-link block h-full">
          {cardContent}
        </a>
      )
    }
    
    // For internal docs links or tab switch links in ApiDocs view, use click handler
    if (isInternalDocsLink || isTabSwitchLink) {
      return (
        <a href={href} onClick={handleClick} className="docs-card-link block h-full cursor-pointer">
          {cardContent}
        </a>
      )
    }
    
    // Standard Next.js Link for all other internal links
    return (
      <Link href={href} className="docs-card-link block h-full">
        {cardContent}
      </Link>
    )
  }
  
  return cardContent
}

interface CardGroupProps {
  children: React.ReactNode
  cols?: 1 | 2 | 3 | 4
  className?: string
}

export function CardGroup({ children, cols = 2, className }: CardGroupProps) {
  const gridCols = {
    1: 'grid-cols-1',
    2: 'grid-cols-1 sm:grid-cols-2',
    3: 'grid-cols-1 sm:grid-cols-2 lg:grid-cols-3',
    4: 'grid-cols-1 sm:grid-cols-2 lg:grid-cols-4',
  }
  
  return (
    <div className={cn('docs-card-group grid gap-4 my-4', gridCols[cols], className)}>
      {children}
    </div>
  )
}

// Alias for Mintlify compatibility
export { CardGroup as Columns }
