import { useState } from 'react'
import { CheckCircle2, AlertTriangle, BarChart3, CheckCheck } from 'lucide-react'
import { cn } from '@/lib/utils'
import { NodeCard } from './NodeCard'
import { SourcePanel } from './SourcePanel'
import type { KBImport, KBNodeEditRequest, KBCommitRequest } from '@/types/kbAccelerator'

interface ReviewScreenProps {
  kbImport: KBImport
  onEditNode: (nodeId: string, data: KBNodeEditRequest) => Promise<void>
  onApproveAll: () => Promise<void>
  onCommit: (data?: KBCommitRequest) => Promise<void>
  onDiscard: () => Promise<void>
  loading: boolean
}

export function ReviewScreen({ kbImport, onEditNode, onApproveAll, onCommit, onDiscard, loading }: ReviewScreenProps) {
  const [highlightExcerpt, setHighlightExcerpt] = useState<string | null>(null)

  const nodes = kbImport.nodes
  const approvedCount = nodes.filter(n => n.user_approved).length
  const lowConfidenceCount = nodes.filter(n => n.confidence_score < 0.65).length
  const avgConfidence = kbImport.confidence_avg ?? 0

  const title = (kbImport.source_metadata as Record<string, unknown> | null)
    ?._conversion as Record<string, unknown> | undefined
  const flowTitle = (title?.title as string) ?? 'Untitled Flow'
  const flowDescription = (title?.description as string) ?? ''

  return (
    <div className="flex flex-col h-full gap-4">
      {/* Header */}
      <div className="card-flat p-4 flex flex-wrap items-center justify-between gap-3">
        <div>
          <h2 className="text-lg font-heading font-semibold text-foreground">{flowTitle}</h2>
          {flowDescription && (
            <p className="text-sm text-muted-foreground mt-0.5">{flowDescription}</p>
          )}
        </div>
        <div className="flex items-center gap-4">
          <div className="flex items-center gap-2 text-sm">
            <BarChart3 size={14} className="text-muted-foreground" />
            <span className="text-muted-foreground">
              Avg confidence: <span className="text-foreground font-medium">{Math.round(avgConfidence * 100)}%</span>
            </span>
          </div>
          <div className="flex items-center gap-2 text-sm">
            <CheckCircle2 size={14} className="text-emerald-400" />
            <span className="text-muted-foreground">
              {approvedCount}/{nodes.length} approved
            </span>
          </div>
          {lowConfidenceCount > 0 && (
            <div className="flex items-center gap-2 text-sm">
              <AlertTriangle size={14} className="text-amber-400" />
              <span className="text-amber-400">
                {lowConfidenceCount} low confidence
              </span>
            </div>
          )}
          {approvedCount < nodes.length && (
            <button
              onClick={onApproveAll}
              disabled={loading}
              className={cn(
                'flex items-center gap-1.5 px-3 py-1.5 rounded-[8px] text-xs font-medium transition-colors',
                'bg-emerald-400/10 border border-emerald-400/20 text-emerald-400',
                'hover:bg-emerald-400/20 hover:border-emerald-400/30',
                'disabled:opacity-50 disabled:cursor-not-allowed'
              )}
            >
              <CheckCheck size={14} />
              Approve All
            </button>
          )}
        </div>
      </div>

      {/* Two-panel layout */}
      <div className="flex-1 grid grid-cols-1 lg:grid-cols-2 gap-4 min-h-0">
        {/* Source panel */}
        <div className="overflow-hidden">
          <SourcePanel
            sourceText={kbImport.source_text}
            sourceFormat={kbImport.source_format}
            highlightExcerpt={highlightExcerpt}
          />
        </div>

        {/* Nodes panel */}
        <div className="flex flex-col card-flat overflow-hidden">
          <div className="flex items-center gap-2 px-4 py-3 border-b" style={{ borderColor: 'var(--color-border-default)' }}>
            <span className="text-sm font-medium text-foreground">Generated Flow</span>
            <span className="font-sans text-xs text-[0.625rem] uppercase tracking-[0.1em] text-muted-foreground ml-auto">
              {kbImport.target_type === 'troubleshooting' ? 'Troubleshooting' : 'Project'}
            </span>
          </div>
          <div className="flex-1 overflow-y-auto p-4 space-y-3">
            {nodes.map(node => (
              <NodeCard
                key={node.id}
                node={node}
                onEdit={onEditNode}
                onHighlight={setHighlightExcerpt}
              />
            ))}
            {nodes.length === 0 && (
              <p className="text-sm text-muted-foreground text-center py-8">
                No nodes generated. Try converting again.
              </p>
            )}
          </div>
        </div>
      </div>

      {/* Actions */}
      <div className="shrink-0 flex items-center justify-between gap-3 pb-1">
        <button
          onClick={onDiscard}
          disabled={loading}
          className={cn(
            'px-4 py-2.5 rounded-lg text-sm font-medium transition-colors',
            'bg-[rgba(255,255,255,0.04)] border border-[rgba(255,255,255,0.06)] text-muted-foreground',
            'hover:text-foreground hover:border-[rgba(255,255,255,0.12)]',
            'disabled:opacity-50 disabled:cursor-not-allowed'
          )}
        >
          Discard
        </button>
        <button
          onClick={() => onCommit()}
          disabled={loading || nodes.length === 0}
          className={cn(
            'flex items-center gap-2 px-6 py-2.5 rounded-lg text-sm font-semibold transition-all',
            'bg-primary text-white',
            'hover:brightness-110 active:scale-[0.98]',
            'disabled:opacity-50 disabled:cursor-not-allowed'
          )}
        >
          <CheckCircle2 size={16} />
          {loading ? 'Committing...' : 'Commit to Library'}
        </button>
      </div>
    </div>
  )
}
