import { useState } from 'react'
import { Copy, Check } from 'lucide-react'
import type { DecisionRecord } from '@/types'
import { cn } from '@/lib/utils'

interface SessionTimelineProps {
  decisions: DecisionRecord[]
  treeType?: string // 'procedural' or 'troubleshooting' (default)
  startedAt: string
  completedAt: string | null
  showCopyButtons?: boolean // default true
}

function formatDate(dateString: string) {
  return new Date(dateString).toLocaleString()
}

function formatDuration(durationSeconds: number | null | undefined) {
  if (durationSeconds == null || durationSeconds < 0) return null
  if (durationSeconds < 60) return `${durationSeconds}s`
  const hours = Math.floor(durationSeconds / 3600)
  const minutes = Math.floor((durationSeconds % 3600) / 60)
  const seconds = durationSeconds % 60
  if (hours > 0) return seconds > 0 ? `${hours}h ${minutes}m ${seconds}s` : `${hours}h ${minutes}m`
  return seconds > 0 ? `${minutes}m ${seconds}s` : `${minutes}m`
}

export function SessionTimeline({
  decisions,
  treeType,
  startedAt,
  completedAt,
  showCopyButtons = true,
}: SessionTimelineProps) {
  const [copiedStepIndex, setCopiedStepIndex] = useState<number | null>(null)

  const handleCopyStep = async (decision: DecisionRecord, index: number) => {
    const lines: string[] = []
    if (decision.question) lines.push(`Question: ${decision.question}`)
    if (decision.answer) lines.push(`Answer: ${decision.answer}`)
    if (decision.action_performed) lines.push(`Action: ${decision.action_performed}`)
    if (decision.notes) lines.push(`Notes: ${decision.notes}`)
    if (decision.command_output) lines.push(`Output:\n${decision.command_output}`)
    try {
      await navigator.clipboard.writeText(lines.join('\n'))
      setCopiedStepIndex(index)
      setTimeout(() => setCopiedStepIndex(null), 2000)
    } catch {
      // Clipboard access denied
    }
  }

  if (treeType === 'procedural') {
    return (
      <div className="mb-8">
        <h2 className="mb-4 text-lg font-semibold text-foreground">Procedure Steps</h2>
        <div className="space-y-2">
          {decisions.map((decision, index) => {
            const isCompleted = decision.answer === 'completed'
            return (
              <div
                key={index}
                className={cn(
                  'bg-card border border-border rounded-xl p-4',
                  isCompleted && 'border-l-2 border-emerald-400/50'
                )}
              >
                <div className="flex items-start gap-3">
                  <span className={cn(
                    'mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-full text-xs font-medium',
                    isCompleted ? 'bg-emerald-400/10 text-emerald-400' : 'bg-accent text-muted-foreground'
                  )}>
                    {isCompleted ? '\u2713' : index + 1}
                  </span>
                  <div className="min-w-0 flex-1">
                    <p className="font-medium text-foreground">{decision.question || 'Step'}</p>
                    {decision.notes && (
                      <p className="mt-1.5 rounded bg-white/5 p-2 text-sm text-muted-foreground">
                        Notes: {decision.notes}
                      </p>
                    )}
                    {decision.command_output && (
                      <p className="mt-1 text-sm text-muted-foreground">
                        Verification: {decision.command_output}
                      </p>
                    )}
                    {decision.duration_seconds != null && (
                      <p className="mt-1 text-xs text-muted-foreground">
                        Duration: {formatDuration(decision.duration_seconds)}
                      </p>
                    )}
                  </div>
                  {showCopyButtons && (
                    <button
                      onClick={() => handleCopyStep(decision, index)}
                      title="Copy step to clipboard"
                      className="rounded p-1 text-muted-foreground hover:bg-accent hover:text-foreground"
                    >
                      {copiedStepIndex === index ? (
                        <Check className="h-4 w-4 text-emerald-400" />
                      ) : (
                        <Copy className="h-4 w-4" />
                      )}
                    </button>
                  )}
                </div>
              </div>
            )
          })}
          {completedAt && (
            <div className="flex items-center gap-3 pl-2 pt-2 text-sm">
              <span className="h-3 w-3 rounded-full bg-emerald-500" />
              <span className="text-emerald-400">
                Procedure completed: {formatDate(completedAt)}
              </span>
            </div>
          )}
        </div>
      </div>
    )
  }

  // Default: troubleshooting decision timeline
  return (
    <div className="mb-8">
      <h2 className="mb-4 text-lg font-semibold text-foreground">Decision Timeline</h2>
      <div className="space-y-4">
        <div className="flex items-center gap-3 text-sm">
          <span className="h-3 w-3 rounded-full bg-foreground" />
          <span className="text-muted-foreground">
            Session started: {formatDate(startedAt)}
          </span>
        </div>

        {decisions.map((decision, index) => (
          <div key={index} className="ml-1 border-l-2 border-border pl-6">
            <div className="relative">
              <span className="absolute -left-[1.625rem] top-1 h-2 w-2 rounded-full bg-muted-foreground" />
              <div className="bg-card border border-border rounded-xl p-4">
                <div className="flex items-start justify-between gap-2">
                  <div className="flex-1">
                    {decision.question && (
                      <p className="font-medium text-foreground">{decision.question}</p>
                    )}
                    {decision.answer && (
                      <p className="mt-1 text-sm text-foreground">Answer: {decision.answer}</p>
                    )}
                    {decision.action_performed && (
                      <p className="mt-1 text-sm text-muted-foreground">
                        Action: {decision.action_performed}
                      </p>
                    )}
                    {decision.notes && (
                      <p className="mt-2 rounded bg-white/5 p-2 text-sm text-muted-foreground">
                        Notes: {decision.notes}
                      </p>
                    )}
                    {decision.command_output && (
                      <div className="mt-2">
                        <p className="mb-1 text-xs font-medium text-muted-foreground">Command Output</p>
                        <pre className="overflow-x-auto rounded bg-white/5 p-2 text-xs font-mono text-muted-foreground whitespace-pre-wrap">
                          {decision.command_output}
                        </pre>
                      </div>
                    )}
                    {decision.duration_seconds != null && (
                      <p className="mt-2 text-xs text-muted-foreground">
                        Duration: {formatDuration(decision.duration_seconds)}
                      </p>
                    )}
                    <p className="mt-2 text-xs text-muted-foreground">
                      {formatDate(decision.timestamp)}
                    </p>
                  </div>
                  {showCopyButtons && (
                    <button
                      onClick={() => handleCopyStep(decision, index)}
                      title="Copy step to clipboard"
                      className="rounded p-1 text-muted-foreground hover:bg-accent hover:text-foreground"
                    >
                      {copiedStepIndex === index ? (
                        <Check className="h-4 w-4 text-emerald-400" />
                      ) : (
                        <Copy className="h-4 w-4" />
                      )}
                    </button>
                  )}
                </div>
              </div>
            </div>
          </div>
        ))}

        {completedAt && (
          <div className="flex items-center gap-3 text-sm">
            <span className="h-3 w-3 rounded-full bg-green-500" />
            <span className="text-emerald-400">
              Session completed: {formatDate(completedAt)}
            </span>
          </div>
        )}
      </div>
    </div>
  )
}

export default SessionTimeline
