import type { ReactNode } from 'react'
import { cn } from '@/lib/utils'
import { Button } from '../basic/button'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '../basic/dropdown-menu'
import { CloseLine, ArrowDownSLine, WarningLine, SparklingLine } from '../basic/icons-inline'
import { Scrollbar } from '../basic/scrollbar'

export interface HintBannerProps {
  type?: 'wiki' | 'credits'
  title?: string
  description?: string
  highlightText?: string
  language?: string
  rechargeText?: string
  onClose?: () => void
  onGenerate?: () => void
  onRecharge?: () => void
  onLanguageChange?: (language: string) => void
  closeIcon?: ReactNode
  arrowDownSIcon?: ReactNode
  suggestionIcon?: ReactNode
  /** 供 Portal 浮层继承（与 ChatInput FolderButton 一致），不传则由 dropdown-menu 使用 getThemeFromDocument() 兜底 */
  dataStyle?: string
  dataTheme?: string
}

const DEFAULT_HIGHLIGHT = 'Repo Wiki'
const LANGUAGES = ['English', '中文', '日本語', '한국어']

const closeClass = 'h-3.5 w-3.5'
const arrowClass = 'h-3 w-3'
const suggestionClass = 'h-4 w-4'

export function HintBanner({
  type = 'wiki',
  title,
  description,
  highlightText = DEFAULT_HIGHLIGHT,
  language = 'English',
  rechargeText,
  onClose,
  onGenerate,
  onRecharge,
  onLanguageChange,
  closeIcon,
  arrowDownSIcon,
  suggestionIcon,
  dataStyle,
  dataTheme,
}: HintBannerProps) {
  const isCreditsType = type === 'credits'
  const defaultClose = closeIcon ?? <CloseLine className={closeClass} />
  const defaultArrow = arrowDownSIcon ?? <ArrowDownSLine className={arrowClass} />
  const defaultSuggestion =
    suggestionIcon ?? (isCreditsType ? <WarningLine className={suggestionClass} /> : <SparklingLine className={suggestionClass} />)

  const displayTitle =
    title ?? (isCreditsType ? 'Credits Exhausted' : 'Free Wiki Generation Available')

  const descriptionTemplate = isCreditsType
    ? 'Your credits have been exhausted. Please recharge to continue using.'
    : `Generate ${highlightText} for this repository to boost AI agent with structured context.`
  const displayDescription = description ?? descriptionTemplate

  const renderDescription = (): ReactNode => {
    if (!displayDescription.includes(highlightText)) {
      return <span>{displayDescription}</span>
    }
    const parts = displayDescription.split(highlightText)
    const result: ReactNode[] = []
    for (let i = 0; i < parts.length; i++) {
      if (parts[i]) {
        result.push(<span key={`text-${i}`}>{parts[i]}</span>)
      }
      if (i < parts.length - 1) {
        result.push(
          <span key={`highlight-${i}`} className="text-[var(--color-link)]">
            {highlightText}
          </span>
        )
      }
    }
    return <>{result}</>
  }

  return (
    <div className="relative rounded-lg border border-border-tertiary bg-bg-base p-3">
      {onClose && (
        <button
          type="button"
          onClick={onClose}
          className="absolute top-3 right-3 flex h-4 w-4 cursor-pointer items-center justify-center rounded-sm text-text-secondary transition-colors duration-200 hover:text-text focus:outline-none focus-visible:ring-2 focus-visible:ring-primary-border"
          aria-label="Close"
        >
          {defaultClose}
        </button>
      )}

      <div className="mb-1 flex items-center gap-2">
        <div
          className={cn(
            'flex h-4 w-4 shrink-0 items-center justify-center',
            isCreditsType ? 'text-warning' : 'text-primary'
          )}
        >
          {defaultSuggestion}
        </div>
        <h3 className="min-w-0 flex-1 text-base leading-base font-semibold text-text">
          {displayTitle}
        </h3>
      </div>

      <>
        <Scrollbar
          scrollbarVisibility="auto"
          maxHeight={96}
          className="mb-2 ml-6 text-xs leading-xs text-text-tertiary"
        >
          {renderDescription()}
        </Scrollbar>
      </>

      <div className="flex items-center justify-end gap-2">
        {isCreditsType ? (
          rechargeText && (
            <Button variant="secondary" onClick={onRecharge}>
              {rechargeText ?? '前往充值'}
            </Button>
          )
        ) : (
          <>
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost" className="flex items-center gap-1">
                  <span>{language}</span>
                  {defaultArrow}
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent dataStyle={dataStyle} dataTheme={dataTheme}>
                {LANGUAGES.map((lang) => (
                  <DropdownMenuItem
                    key={lang}
                    onSelect={() => onLanguageChange?.(lang)}
                  >
                    {lang}
                  </DropdownMenuItem>
                ))}
              </DropdownMenuContent>
            </DropdownMenu>
            <Button variant="secondary" onClick={onGenerate}>
              Generate
            </Button>
          </>
        )}
      </div>
    </div>
  )
}

HintBanner.displayName = 'HintBanner'
