'use client'

import { CheckCircle2, AlertCircle, Info, BarChart3 } from 'lucide-react'
import { cn } from '@/lib/utils'
import { debugProps } from '@/lib/debug'

export interface IssueItem {
  category: 'structure' | 'logic' | 'risk' | 'pattern'
  severity: 'error' | 'warning' | 'info'
  suggestion: string
}

export interface ReviewRound {
  round: number
  model: string
  role: string
  focus: string
  issues: IssueItem[]
  score: number
  plan_diff_lines: number
  converged: boolean
  timestamp: string
}

export interface ReviewLog {
  plan_file: string
  created_at: string
  rounds: ReviewRound[]
  convergence?: {
    stable_at_round: number
    final_diff_pct: number
    convergence_metric: string
  }
  approval: {
    status: 'pending' | 'approved' | 'rejected'
    timestamp?: string
  }
  summary: string
}

interface ReviewLogViewerProps {
  reviewLog: ReviewLog
}

const SEVERITY_COLORS: Record<IssueItem['severity'], string> = {
  error: 'text-status-blocked bg-status-blocked/10 border-status-blocked/30',
  warning: 'text-status-in-progress bg-status-in-progress/10 border-status-in-progress/30',
  info: 'text-status-review bg-status-review/10 border-status-review/30',
}

const CATEGORY_LABELS: Record<IssueItem['category'], string> = {
  structure: 'Structuur',
  logic: 'Logica',
  risk: 'Risico',
  pattern: 'Patroon',
}

const APPROVAL_COLORS: Record<ReviewLog['approval']['status'], string> = {
  pending: 'bg-status-in-progress/15 text-status-in-progress border-status-in-progress/30',
  approved: 'bg-status-done/15 text-status-done border-status-done/30',
  rejected: 'bg-status-blocked/15 text-status-blocked border-status-blocked/30',
}

const APPROVAL_LABELS: Record<ReviewLog['approval']['status'], string> = {
  pending: 'In behandeling',
  approved: 'Goedgekeurd',
  rejected: 'Afgewezen',
}

function IssueIcon({ severity }: { severity: IssueItem['severity'] }) {
  switch (severity) {
    case 'error':
      return <AlertCircle className="size-4" />
    case 'warning':
      return <AlertCircle className="size-4" />
    case 'info':
      return <Info className="size-4" />
  }
}

function RoundHeader({ round }: { round: ReviewRound }) {
  const date = new Date(round.timestamp).toLocaleString('nl-NL', {
    dateStyle: 'short',
    timeStyle: 'short',
  })

  return (
    <div className="flex items-center justify-between gap-4 mb-3">
      <div className="flex items-center gap-3">
        <div className="flex items-center gap-1.5">
          <span className="text-xs font-mono px-2 py-0.5 rounded bg-muted text-muted-foreground">
            Ronde {round.round + 1}
          </span>
          <span className="text-xs font-mono px-2 py-0.5 rounded border border-border bg-surface-container text-muted-foreground">
            {round.model.split('-').pop()?.toUpperCase()}
          </span>
        </div>
        <div className="flex items-center gap-2">
          <span className="text-sm font-medium">{round.role}</span>
          {round.converged && (
            <span className="text-xs px-1.5 py-0.5 rounded-full bg-status-done/20 text-status-done border border-status-done/30">
              Converged
            </span>
          )}
        </div>
      </div>
      <span className="text-xs text-muted-foreground">{date}</span>
    </div>
  )
}

function RoundStats({ round }: { round: ReviewRound }) {
  return (
    <div className="grid grid-cols-2 gap-2 mb-3 text-xs">
      <div className="flex items-center gap-2 p-2 rounded bg-surface-container">
        <BarChart3 className="size-4 text-muted-foreground" />
        <div>
          <div className="text-muted-foreground">Score</div>
          <div className="font-medium">{round.score}/100</div>
        </div>
      </div>
      <div className="flex items-center gap-2 p-2 rounded bg-surface-container">
        <AlertCircle className="size-4 text-muted-foreground" />
        <div>
          <div className="text-muted-foreground">Wijzigingen</div>
          <div className="font-medium">{round.plan_diff_lines} regels</div>
        </div>
      </div>
    </div>
  )
}

function IssueBadge({ issue, index }: { issue: IssueItem; index: number }) {
  return (
    <div key={index} className={cn('rounded border p-2 text-xs', SEVERITY_COLORS[issue.severity])}>
      <div className="flex items-start gap-2">
        <IssueIcon severity={issue.severity} />
        <div className="flex-1">
          <div className="font-medium">{CATEGORY_LABELS[issue.category]}</div>
          <p className="text-xs mt-1 opacity-90">{issue.suggestion}</p>
        </div>
      </div>
    </div>
  )
}

export function ReviewLogViewer({ reviewLog }: ReviewLogViewerProps) {
  const approvalDate = reviewLog.approval.timestamp
    ? new Date(reviewLog.approval.timestamp).toLocaleString('nl-NL', {
        dateStyle: 'short',
        timeStyle: 'short',
      })
    : null

  return (
    <div
      className="space-y-4"
      {...debugProps('review-log-viewer', 'ReviewLogViewer', 'components/ideas/review-log-viewer.tsx')}
    >
      {/* Summary */}
      <div className="rounded-lg border border-input bg-surface-container p-4 space-y-2">
        <div className="flex items-center justify-between">
          <h3 className="font-semibold text-sm">Plan-beoordeling</h3>
          <span
            className={cn(
              'text-xs px-2.5 py-1 rounded-full border font-medium',
              APPROVAL_COLORS[reviewLog.approval.status],
            )}
          >
            {APPROVAL_LABELS[reviewLog.approval.status]}
          </span>
        </div>
        <p className="text-sm text-foreground">{reviewLog.summary}</p>
        {approvalDate && (
          <p className="text-xs text-muted-foreground">Goedgekeurd op {approvalDate}</p>
        )}
      </div>

      {/* Convergence Metrics */}
      {reviewLog.convergence && (
        <div className="rounded-lg border border-input bg-surface-container p-4 space-y-3">
          <h3 className="font-semibold text-sm flex items-center gap-2">
            <CheckCircle2 className="size-4 text-status-done" />
            Convergentie
          </h3>
          <div className="grid grid-cols-2 gap-3">
            <div className="p-2 rounded bg-surface-container-low">
              <p className="text-xs text-muted-foreground">Stabiel na ronde</p>
              <p className="font-semibold text-lg">{reviewLog.convergence.stable_at_round + 1}</p>
            </div>
            <div className="p-2 rounded bg-surface-container-low">
              <p className="text-xs text-muted-foreground">Eindwijziging</p>
              <p className="font-semibold text-lg">{reviewLog.convergence.final_diff_pct.toFixed(1)}%</p>
            </div>
          </div>
        </div>
      )}

      {/* Review Rounds */}
      <div className="space-y-4">
        <h3 className="font-semibold text-sm px-2">Review-rondes</h3>
        {reviewLog.rounds.map((round) => (
          <div key={round.round} className="rounded-lg border border-input bg-surface-container p-4 space-y-3">
            <RoundHeader round={round} />
            <RoundStats round={round} />

            {/* Issues */}
            {round.issues.length > 0 ? (
              <div className="space-y-2">
                <h4 className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
                  Bevindingen ({round.issues.length})
                </h4>
                <div className="space-y-2">
                  {round.issues.map((issue, idx) => (
                    <IssueBadge key={idx} issue={issue} index={idx} />
                  ))}
                </div>
              </div>
            ) : (
              <p className="text-xs text-muted-foreground italic">Geen bevindingen in deze ronde.</p>
            )}
          </div>
        ))}
      </div>

      {/* Metadata */}
      <div className="text-xs text-muted-foreground p-2 rounded bg-surface-container-low space-y-1">
        <p>
          <span className="font-medium">Bestand:</span> {reviewLog.plan_file}
        </p>
        <p>
          <span className="font-medium">Gemaakt:</span>{' '}
          {new Date(reviewLog.created_at).toLocaleString('nl-NL', { dateStyle: 'short', timeStyle: 'short' })}
        </p>
        <p>
          <span className="font-medium">Rondes:</span> {reviewLog.rounds.length}
        </p>
      </div>
    </div>
  )
}
