import type { ReactNode } from 'react'
import { cn } from '@/lib/utils'
import { CollapsibleCard } from '../basic/collapsible-card'
import { Button } from '../basic/button'
import { IconButton } from '../basic/icon-button'
import { FileList2Line, CheckLine, DownloadLine } from '../basic/icons-inline'

const ICON_CLASS = 'w-[var(--font-size-sm)] h-[var(--font-size-sm)] shrink-0'

export interface PlanPartProps {
  title?: string
  description?: string
  content: string
  viewText?: string
  buildText?: string
  builtText?: string
  isBuilt?: boolean
  isGenerating?: boolean
  onView?: () => void
  onBuild?: () => void
  onDownload?: () => void
  defaultExpanded?: boolean
  contentMaxHeight?: number
  collapsible?: boolean
  className?: string
  headerIcon?: ReactNode
  downloadIcon?: ReactNode
  builtIcon?: ReactNode
}

const defaultHeaderIcon = <FileList2Line className={`${ICON_CLASS} text-text-secondary`} />
const defaultDownloadIcon = <DownloadLine className={ICON_CLASS} />
const defaultBuiltIcon = <CheckLine className={cn(ICON_CLASS, 'text-success')} />

export function PlanPart({
  title = 'Plan',
  description,
  content,
  viewText = 'View',
  buildText = 'Build ⌘⏎',
  builtText = 'Built',
  isBuilt = false,
  isGenerating = false,
  onView,
  onBuild,
  onDownload,
  defaultExpanded = true,
  contentMaxHeight,
  collapsible = false,
  className,
  headerIcon,
  downloadIcon,
  builtIcon,
}: PlanPartProps) {
  const lines = content.split('\n')
  const hasTitle = lines.length > 1 && lines[1].trim() === ''
  const contentTitle = hasTitle ? lines[0] : null
  const contentBody = hasTitle ? lines.slice(2).join('\n') : content

  return (
    <CollapsibleCard
      headerIcon={headerIcon ?? defaultHeaderIcon}
      headerTitle={
        <div className="flex items-center gap-2 flex-1 min-w-0">
          {isGenerating ? (
            <span className="text-left">Planning...</span>
          ) : (
            <>
              <span className="text-left">{title}</span>
              {description != null && (
                <span className="text-left flex-1 truncate text-text-quaternary">{description}</span>
              )}
            </>
          )}
        </div>
      }
      titleShimmer={isGenerating}
      headerRight={
        !isGenerating && onDownload ? (
          <IconButton
            variant="iconOnly"
            size="sm"
            icon={downloadIcon ?? defaultDownloadIcon}
            onClick={(e) => { e.stopPropagation(); onDownload?.() }}
            title="Download as Markdown"
            aria-label="Download"
            className="!min-h-0 !min-w-0 h-[var(--font-size-sm)] w-[var(--font-size-sm)] text-text-secondary hover:text-text [&_svg]:w-[var(--font-size-sm)] [&_svg]:h-[var(--font-size-sm)]"
          />
        ) : undefined
      }
      contentPadding="var(--spacing-1\.5) var(--spacing-2)"
      defaultExpanded={defaultExpanded}
      contentMaxHeight={contentMaxHeight}
      collapsible={collapsible}
      footer={
        !isGenerating ? (
          <>
            <Button variant="text" size="sm" onClick={onView}>
              {viewText}
            </Button>
            <div className="flex-1" />
            {isBuilt ? (
              <div className="flex items-center gap-1 text-xs text-success [&>svg]:w-[var(--font-size-sm)] [&>svg]:h-[var(--font-size-sm)]">
                <span>{builtText}</span>
                {builtIcon ?? defaultBuiltIcon}
              </div>
            ) : (
              <Button variant="secondary" size="sm" onClick={onBuild}>
                {buildText}
              </Button>
            )}
          </>
        ) : undefined
      }
      className={className}
    >
      {isGenerating ? (
        <div className="flex flex-col gap-1 relative overflow-hidden min-h-[var(--spacing-14)]">
          {/* 点阵背景层 - 基础灰色点（与 QodeChatPanel PlanPart 一致） */}
          <div
            className="absolute inset-0 pointer-events-none"
            style={{
              backgroundImage: 'radial-gradient(circle, var(--color-text-tertiary) 1px, transparent 1px)',
              backgroundSize: '16px 16px',
              backgroundRepeat: 'repeat',
              opacity: 0.25,
            }}
          />
          {/* 逐行点亮的点阵层 - 高亮带的竖向移动动画（与 QodeChatPanel 一致） */}
          <div
            className="absolute inset-0 pointer-events-none plan-part-shimmer-layer"
            style={{
              backgroundImage: 'radial-gradient(circle, var(--color-text-tertiary) 1px, transparent 1px)',
              backgroundSize: '16px 16px',
              backgroundRepeat: 'repeat',
              maskImage: 'linear-gradient(to bottom, transparent 0%, var(--color-mask-shimmer-weak) 15%, var(--color-mask-shimmer-strong) 30%, var(--color-mask-shimmer-full) 50%, var(--color-mask-shimmer-strong) 70%, var(--color-mask-shimmer-weak) 85%, transparent 100%)',
              maskSize: '100% 64px',
              WebkitMaskImage: 'linear-gradient(to bottom, transparent 0%, var(--color-mask-shimmer-weak) 15%, var(--color-mask-shimmer-strong) 30%, var(--color-mask-shimmer-full) 50%, var(--color-mask-shimmer-strong) 70%, var(--color-mask-shimmer-weak) 85%, transparent 100%)',
              WebkitMaskSize: '100% 64px',
            }}
          />
          <style>{`
            @keyframes plan-part-shimmer {
              0% { mask-position: 0 -64px; -webkit-mask-position: 0 -64px; }
              100% { mask-position: 0 calc(100% + 64px); -webkit-mask-position: 0 calc(100% + 64px); }
            }
            .plan-part-shimmer-layer {
              animation: plan-part-shimmer 3s linear infinite;
            }
          `}</style>
        </div>
      ) : (
        <div className="flex flex-col gap-1">
          {contentTitle != null && (
            <div className="text-sm font-medium text-text">{contentTitle}</div>
          )}
          {contentBody != null && contentBody !== '' && (
            <span className="text-xs leading-xs text-text whitespace-pre-wrap break-words">
              {contentBody}
            </span>
          )}
        </div>
      )}
    </CollapsibleCard>
  )
}

PlanPart.displayName = 'PlanPart'
export const AgentPlanCard = PlanPart
export type AgentPlanCardProps = PlanPartProps
