import { CheckCircle2, Clock, FileText, Download } from 'lucide-react'
import type { ProceduralStep } from '@/types'

interface StepCompletion {
  stepId: string
  notes: string
  verificationValue: string
  completedAt: string
}

interface CompletionSummaryProps {
  treeName: string
  steps: ProceduralStep[]
  completions: Map<string, StepCompletion>
  variables: Record<string, string>
  startedAt: string
  completedAt: string
  onExport: () => void
  onClose: () => void
}

export function CompletionSummary({
  treeName,
  steps,
  completions,
  variables,
  startedAt,
  completedAt,
  onExport,
  onClose,
}: CompletionSummaryProps) {
  const procedureSteps = steps.filter((s) => s.type === 'procedure_step')

  // Parse backend timestamp — ensure UTC if no timezone info
  const parseTs = (ts: string) => {
    if (!ts.endsWith('Z') && !ts.includes('+') && !/\d{2}:\d{2}$/.test(ts.slice(-5))) {
      return new Date(ts + 'Z')
    }
    return new Date(ts)
  }

  const start = parseTs(startedAt)
  const end = parseTs(completedAt)
  const totalMinutes = Math.max(0, Math.round((end.getTime() - start.getTime()) / 60000))

  const formatTime = (minutes: number) => {
    if (minutes < 1) return '<1 minute'
    if (minutes < 60) return `${minutes} minute${minutes !== 1 ? 's' : ''}`
    const h = Math.floor(minutes / 60)
    const m = minutes % 60
    return m > 0 ? `${h}h ${m}m` : `${h} hour${h > 1 ? 's' : ''}`
  }

  return (
    <div className="mx-auto max-w-2xl space-y-6">
      {/* Success header */}
      <div className="text-center">
        <div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-emerald-400/10">
          <CheckCircle2 className="h-8 w-8 text-emerald-400" />
        </div>
        <h1 className="text-2xl font-bold text-foreground">Procedure Complete</h1>
        <p className="mt-1 text-muted-foreground">{treeName}</p>
      </div>

      {/* Summary stats */}
      <div className="grid grid-cols-3 gap-3">
        <div className="bg-card border border-border rounded-xl p-3 text-center">
          <CheckCircle2 className="mx-auto mb-1 h-5 w-5 text-emerald-400" />
          <div className="text-lg font-semibold text-foreground">{procedureSteps.length}</div>
          <div className="text-xs text-muted-foreground">Steps Completed</div>
        </div>
        <div className="bg-card border border-border rounded-xl p-3 text-center">
          <Clock className="mx-auto mb-1 h-5 w-5 text-muted-foreground" />
          <div className="text-lg font-semibold text-foreground">{formatTime(totalMinutes)}</div>
          <div className="text-xs text-muted-foreground">Total Time</div>
        </div>
        <div className="bg-card border border-border rounded-xl p-3 text-center">
          <FileText className="mx-auto mb-1 h-5 w-5 text-muted-foreground" />
          <div className="text-lg font-semibold text-foreground">{Object.keys(variables).length}</div>
          <div className="text-xs text-muted-foreground">Parameters</div>
        </div>
      </div>

      {/* Project parameters */}
      {Object.keys(variables).length > 0 && (
        <div className="bg-card border border-border rounded-xl p-4">
          <h3 className="mb-3 text-sm font-semibold text-muted-foreground">Project Parameters</h3>
          <div className="space-y-1.5">
            {Object.entries(variables).map(([key, value]) => (
              <div key={key} className="flex items-baseline justify-between gap-4 text-sm">
                <span className="font-mono text-muted-foreground">{key}</span>
                <span className="text-right text-muted-foreground">{value}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Step details */}
      <div className="bg-card border border-border rounded-xl p-4">
        <h3 className="mb-3 text-sm font-semibold text-muted-foreground">Step Summary</h3>
        <div className="space-y-2">
          {procedureSteps.map((step, index) => {
            const completion = completions.get(step.id)
            return (
              <div key={step.id} className="flex items-start gap-2 text-sm">
                <CheckCircle2 className="mt-0.5 h-4 w-4 shrink-0 text-emerald-400" />
                <div className="min-w-0 flex-1">
                  <div className="flex items-center gap-2">
                    <span className="text-muted-foreground">
                      {index + 1}. {step.title}
                    </span>
                  </div>
                  {completion?.notes && (
                    <p className="mt-0.5 text-xs text-muted-foreground">Note: {completion.notes}</p>
                  )}
                  {completion?.verificationValue && (
                    <p className="mt-0.5 text-xs text-muted-foreground">
                      Verified: {completion.verificationValue}
                    </p>
                  )}
                </div>
              </div>
            )
          })}
        </div>
      </div>

      {/* Actions */}
      <div className="flex items-center gap-3">
        <button
          onClick={onExport}
          className="flex flex-1 items-center justify-center gap-2 rounded-lg border border-border px-4 py-2.5 text-sm font-medium text-muted-foreground hover:bg-accent hover:text-foreground"
        >
          <Download className="h-4 w-4" />
          Export Report
        </button>
        <button
          onClick={onClose}
          className="flex flex-1 items-center justify-center gap-2 rounded-lg bg-gradient-brand px-4 py-2.5 text-sm font-medium text-white shadow-lg shadow-primary/20 hover:opacity-90"
        >
          Done
        </button>
      </div>
    </div>
  )
}
