'use client'

import { useState, useEffect } from 'react'
import { ShieldAlert, ChevronDown, XCircle } from 'lucide-react'
import { cn } from '@/lib/utils'
import type { ContentBlock, PermissionStatus } from '@/lib/types'
import { getToolSummary } from './chat-utils'

type PermissionDecision = (requestId: string, decision: 'allow' | 'allow_session' | 'deny') => void

/** Countdown from `total` seconds while `active` is true; freezes otherwise. */
function useCountdown(active: boolean, total = 120) {
  const [remaining, setRemaining] = useState(total)
  useEffect(() => {
    if (!active) return
    const start = Date.now()
    const timer = setInterval(() => {
      setRemaining(Math.max(0, total - Math.floor((Date.now() - start) / 1000)))
    }, 1000)
    return () => clearInterval(timer)
  }, [active, total])
  return remaining
}

/**
 * Grouped permission block: merges multiple same-tool requests (pending or resolved)
 * into a single compact card with expandable details.
 */
export function PermissionGroupBlock({
  requests,
  onDecision,
}: {
  requests: Array<Extract<ContentBlock, { type: 'permission_request' }>>
  onDecision?: PermissionDecision
}) {
  const toolName = requests[0].toolName
  const [expanded, setExpanded] = useState(false)
  const pendingRequests = requests.filter(r => r.status === 'pending')
  const hasPending = pendingRequests.length > 0
  const allResolved = !hasPending

  // Derive group status from individual statuses
  const resolvedStatus = allResolved ? requests[0].status : undefined
  const hasFailure = requests.some(r => r.toolFailed)

  // Countdown timer (only for pending groups)
  const remaining = useCountdown(hasPending)

  const handleDecision = (decision: 'allow' | 'allow_session' | 'deny') => {
    if (!onDecision) return
    for (const req of pendingRequests) {
      onDecision(req.requestId, decision)
    }
  }

  const statusTitle = hasPending ? 'Permission Required'
    : resolvedStatus === 'denied' ? 'Permission Denied'
    : resolvedStatus === 'timeout' ? 'Permission Timed Out'
    : resolvedStatus === 'allowed_session' ? 'Permission Granted (Session)'
    : 'Permission Granted'
  const statusColor = hasPending ? 'text-amber'
    : resolvedStatus === 'timeout' ? 'text-amber'
    : resolvedStatus === 'denied' ? 'text-coral'
    : 'text-green'
  const borderColor = hasPending ? 'border-strong'
    : resolvedStatus === 'timeout' ? 'border-amber/30'
    : resolvedStatus === 'denied' ? 'border-coral/30'
    : 'border-green/30'

  return (
    <div className={cn('rounded-[10px] border overflow-hidden my-2 flex flex-col gap-2.5 p-3.5 bg-elevated', borderColor)}>
      {/* Header */}
      <div className="flex items-center gap-2">
        <ShieldAlert size={16} className={cn(statusColor, 'shrink-0')} />
        <span className={cn('text-[13px] font-semibold', statusColor)}>{statusTitle}</span>
        <span className="text-[11px] text-muted px-1.5 py-0.5 rounded bg-surface-active">{requests.length}</span>
        {hasPending && remaining > 0 && (
          <span className={cn('text-[11px] font-mono tabular-nums ml-auto', remaining <= 30 ? 'text-coral' : 'text-muted')}>
            {remaining}s
          </span>
        )}
      </div>

      {/* Tool failure warning */}
      {allResolved && hasFailure && (
        <div className="flex items-center gap-2 px-2.5 py-1.5 rounded-md bg-coral/10 border border-coral/20">
          <XCircle size={13} className="text-coral shrink-0" />
          <span className="text-[11px] text-coral font-medium">Tool execution failed after permission was granted</span>
        </div>
      )}

      {/* Summary + expandable details */}
      <button
        onClick={() => setExpanded(!expanded)}
        className="flex items-center gap-1.5 text-left"
      >
        <ChevronDown size={12} className={cn('text-tertiary transition-transform shrink-0', expanded && 'rotate-180')} />
        <span className="text-[12px] font-medium text-primary">{toolName}</span>
        <span className="text-[11px] text-muted">{requests.length} requests</span>
      </button>
      {expanded && (
        <div className="ml-5 flex flex-col gap-1.5">
          {requests.map((req) => {
            const summary = getToolSummary(req.toolName, req.toolInput)
            return (
              <p key={req.requestId} className="text-[11px] text-secondary font-mono truncate">
                {summary || JSON.stringify(req.toolInput).slice(0, 80)}
              </p>
            )
          })}
        </div>
      )}

      {/* Action Buttons — only for pending */}
      {hasPending && onDecision && (
        <div className="flex items-center justify-end gap-2">
          <button
            onClick={() => handleDecision('deny')}
            className="px-3.5 py-1.5 rounded-md border border-strong text-[11px] font-medium text-secondary hover:bg-surface-hover transition-colors"
          >
            Deny
          </button>
          <button
            onClick={() => handleDecision('allow_session')}
            className="px-3.5 py-1.5 rounded-md border border-indigo/30 bg-indigo/10 text-[11px] font-medium text-indigo hover:bg-indigo/20 transition-colors"
          >
            Allow Session
          </button>
          <button
            onClick={() => handleDecision('allow')}
            className="px-3.5 py-1.5 rounded-md bg-brand-primary text-on-primary text-[11px] font-medium hover:bg-brand-primary-hover active:bg-brand-primary-active active:scale-[0.97] transition-colors focus:outline-none focus-visible:shadow-focus-ring"
          >
            Allow
          </button>
        </div>
      )}
    </div>
  )
}

export function PermissionBlock({
  requestId,
  toolName,
  toolInput,
  status,
  toolFailed,
  onDecision,
}: {
  requestId: string
  toolName: string
  toolInput: Record<string, unknown>
  status: PermissionStatus
  toolFailed?: boolean
  onDecision?: PermissionDecision
}) {
  const summary = getToolSummary(toolName, toolInput)
  const isPending = status === 'pending'
  const isAllowed = status === 'allowed' || status === 'allowed_session'

  // Countdown timer for pending permissions (120s timeout)
  const remaining = useCountdown(isPending)

  // Expanded state for long tool inputs
  const [inputExpanded, setInputExpanded] = useState(false)
  const commandStr = toolInput.command ? String(toolInput.command) : ''
  const isLongCommand = commandStr.length > 100

  const statusTitle = isPending ? 'Permission Required'
    : status === 'denied' ? 'Permission Denied'
    : status === 'timeout' ? 'Permission Timed Out'
    : status === 'allowed_session' ? 'Permission Granted (Session)'
    : 'Permission Granted'
  // Timeout uses amber, deny uses coral, allowed uses green
  const statusColor = isPending ? 'text-amber'
    : status === 'timeout' ? 'text-amber'
    : status === 'denied' ? 'text-coral'
    : 'text-green'
  const borderColor = isPending ? 'border-strong'
    : status === 'timeout' ? 'border-amber/30'
    : status === 'denied' ? 'border-coral/30'
    : 'border-green/30'

  return (
    <div className={cn(
      'rounded-[10px] border overflow-hidden my-2 flex flex-col gap-3 p-3.5 bg-elevated',
      borderColor,
    )}>
      {/* Header */}
      <div className="flex items-center gap-2">
        <ShieldAlert size={16} className={cn(statusColor, 'shrink-0')} />
        <span className={cn('text-[13px] font-semibold', statusColor)}>{statusTitle}</span>
        {isPending && remaining > 0 && (
          <span className={cn('text-[11px] font-mono tabular-nums ml-auto', remaining <= 30 ? 'text-coral' : 'text-muted')}>
            {remaining}s
          </span>
        )}
      </div>

      {/* Tool failure warning — shown when permission was granted but tool execution failed */}
      {isAllowed && toolFailed && (
        <div className="flex items-center gap-2 px-2.5 py-1.5 rounded-md bg-coral/10 border border-coral/20">
          <XCircle size={13} className="text-coral shrink-0" />
          <span className="text-[11px] text-coral font-medium">Tool execution failed after permission was granted</span>
        </div>
      )}

      {/* Description */}
      <div className="flex flex-col gap-1">
        <p className="text-[12px] font-medium text-primary">
          {toolName}{summary ? `  ${summary}` : ''}
        </p>
        {commandStr && (
          <div>
            <p className="text-[12px] text-secondary font-mono whitespace-pre-wrap break-all">
              {isLongCommand && !inputExpanded ? commandStr.slice(0, 100) + '...' : commandStr}
            </p>
            {isLongCommand && (
              <button
                onClick={() => setInputExpanded(!inputExpanded)}
                className="text-[11px] text-indigo hover:underline mt-0.5"
              >
                {inputExpanded ? 'Show less' : 'Show full command'}
              </button>
            )}
          </div>
        )}
        {!!toolInput.file_path && !summary && (
          <p className="text-[12px] text-secondary">{String(toolInput.file_path)}</p>
        )}
        {/* Show content for Write/Edit tools in pending state so user can review */}
        {isPending && typeof toolInput.content === 'string' && (toolName === 'Write' || toolName === 'Edit') && (() => {
          const contentStr = toolInput.content as string
          return (
            <details className="mt-1">
              <summary className="text-[11px] text-indigo cursor-pointer hover:underline">View file content</summary>
              <pre className="mt-1 px-2 py-1.5 rounded bg-surface text-[11px] font-mono text-secondary max-h-[200px] overflow-y-auto whitespace-pre-wrap">
                {contentStr.slice(0, 2000)}{contentStr.length > 2000 ? '\n[truncated]' : ''}
              </pre>
            </details>
          )
        })()}
      </div>

      {/* Action Buttons */}
      {isPending && onDecision && (
        <div className="flex items-center justify-end gap-2">
          <button
            onClick={() => onDecision(requestId, 'deny')}
            className="px-3.5 py-1.5 rounded-md border border-strong text-[11px] font-medium text-secondary hover:bg-surface-hover transition-colors"
          >
            Deny
          </button>
          <button
            onClick={() => onDecision(requestId, 'allow_session')}
            className="px-3.5 py-1.5 rounded-md border border-indigo/30 bg-indigo/10 text-[11px] font-medium text-indigo hover:bg-indigo/20 transition-colors"
          >
            Allow Session
          </button>
          <button
            onClick={() => onDecision(requestId, 'allow')}
            className="px-3.5 py-1.5 rounded-md bg-brand-primary text-on-primary text-[11px] font-medium hover:bg-brand-primary-hover active:bg-brand-primary-active active:scale-[0.97] transition-colors focus:outline-none focus-visible:shadow-focus-ring"
          >
            Allow
          </button>
        </div>
      )}
    </div>
  )
}
