import { useState, type ReactNode } from 'react'
import { CollapsibleCard } from '../basic/collapsible-card'
import { Button } from '../basic/button'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '../basic/select'
import { GlobalLine, WarningLine, Forbid2Line } from '../basic/icons-inline'

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

export type BrowserActionStatus = 'normal' | 'failed' | 'skipped'

export interface BrowserActionPartProps {
  description?: string
  content?: string
  status?: BrowserActionStatus
  onRun?: () => void
  onSkip?: () => void
  onViewDetail?: () => void
  onAskEveryTimeChange?: (value: string) => void
  className?: string
  /** 供 Select 下拉浮层继承布局风格（如 dense），不传则从 document 读取 */
  dataStyle?: string
  /** 供 Select 下拉浮层继承颜色主题，不传则从 document 读取 */
  dataTheme?: string
  normalIcon?: ReactNode
  failedIcon?: ReactNode
  skippedIcon?: ReactNode
}

const defaultNormalIcon = <GlobalLine className={`${ICON_CLASS} text-text-secondary`} />
const defaultFailedIcon = <WarningLine className={`${ICON_CLASS} text-warning`} />
const defaultSkippedIcon = <Forbid2Line className={`${ICON_CLASS} text-text-secondary`} />

function BrowserFooter({
  askValue,
  onAskChange,
  onSkip,
  onRun,
  dataStyle,
  dataTheme,
}: {
  askValue: string
  onAskChange: (value: string) => void
  onSkip: () => void
  onRun: () => void
  dataStyle?: string
  dataTheme?: string
}) {
  return (
    <div className="flex items-center gap-2 flex-1 min-w-0">
      <div className="shrink-0 w-fit">
        <Select value={askValue} onValueChange={onAskChange}>
          <SelectTrigger
            className="h-7 w-auto min-w-0 border-0 bg-transparent px-2 py-0 text-xs text-text-tertiary hover:text-text [&>svg]:w-[var(--font-size-sm)] [&>svg]:h-[var(--font-size-sm)]"
            onClick={(e) => e.stopPropagation()}
          >
            <SelectValue />
          </SelectTrigger>
          <SelectContent
            dataStyle={dataStyle}
            dataTheme={dataTheme}
            onClick={(e) => e.stopPropagation()}
          >
            <SelectItem value="Ask every time">Ask every time</SelectItem>
            <SelectItem value="Always allow">Always allow</SelectItem>
            <SelectItem value="Always deny">Always deny</SelectItem>
          </SelectContent>
        </Select>
      </div>
      <div className="flex-1 h-4 border-l border-border-tertiary opacity-10" />
      <Button variant="ghost" size="sm" onClick={(e) => { e.stopPropagation(); onSkip() }}>
        Skip ⌘⌫
      </Button>
      <Button variant="secondary" size="sm" onClick={(e) => { e.stopPropagation(); onRun() }}>
        Run ⌘⏎
      </Button>
    </div>
  )
}

export function BrowserActionPart({
  description,
  content,
  status = 'normal',
  onRun,
  onSkip,
  onViewDetail,
  onAskEveryTimeChange,
  className,
  dataStyle,
  dataTheme,
  normalIcon,
  failedIcon,
  skippedIcon,
}: BrowserActionPartProps) {
  const [askValue, setAskValue] = useState('Ask every time')

  const handleAskChange = (value: string) => {
    setAskValue(value)
    onAskEveryTimeChange?.(value)
  }

  const headerIcon =
    status === 'failed'
      ? (failedIcon ?? defaultFailedIcon)
      : status === 'skipped'
        ? (skippedIcon ?? defaultSkippedIcon)
        : (normalIcon ?? defaultNormalIcon)

  const headerTitle =
    status === 'failed' ? (
      <span>Browser Failed</span>
    ) : status === 'skipped' ? (
      <span>Browser Skipped</span>
    ) : (
      <div className="flex items-center gap-2 flex-1 min-w-0">
        <span className="shrink-0">Browser</span>
        {description != null && (
          <span className="flex-1 min-w-0 truncate text-text-tertiary">{description}</span>
        )}
      </div>
    )

  const headerRight =
    status === 'failed' ? (
      <Button variant="text" size="sm" onClick={(e) => { e.stopPropagation(); onViewDetail?.() }}>
        View Detail
      </Button>
    ) : undefined

  const footer =
    status === 'normal' ? (
      <BrowserFooter
        askValue={askValue}
        onAskChange={handleAskChange}
        onSkip={() => onSkip?.()}
        onRun={() => onRun?.()}
        dataStyle={dataStyle}
        dataTheme={dataTheme}
      />
    ) : undefined

  return (
    <CollapsibleCard
      headerIcon={headerIcon}
      headerTitle={headerTitle}
      headerRight={headerRight}
      contentPadding="var(--spacing-1\.5) var(--spacing-2)"
      defaultExpanded={status === 'normal'}
      collapsible={status === 'normal'}
      footer={footer}
      className={className}
    >
      {content != null && content !== '' && (
        <span className="text-xs leading-xs text-text whitespace-pre-wrap break-words">{content}</span>
      )}
    </CollapsibleCard>
  )
}

BrowserActionPart.displayName = 'BrowserActionPart'
export const BrowserActionCard = BrowserActionPart
export type BrowserActionCardProps = BrowserActionPartProps
