'use client'

import { useEffect, useRef } from 'react'
import { Check, Copy, Loader2, Sparkles, X } from 'lucide-react'
import type { CoauthorAction, ProofreadChange } from '../lib/coauthor-client.js'
import { coauthorActionLabel } from '../lib/coauthor-client.js'

export interface CoauthorResultPopoverProps {
  open: boolean
  loading: boolean
  action: CoauthorAction
  before: string
  after: string
  error?: string
  changes?: ProofreadChange[]
  /** Label for the apply target, e.g. "Apply to editor" or "Replace selection". */
  applyLabel?: string
  onApply: () => void
  onCopy: () => void
  onDiscard: () => void
}

/**
 * Universal AI-result panel rendered by both the TipTap bubble menu and the
 * Cmd+K slash-command palette. Shows a before/after diff plus three actions:
 *
 *   - Apply (write the result back to the active target)
 *   - Copy (copy the result to the clipboard)
 *   - Discard (close without changing anything)
 *
 * The popover takes the same `{ open, loading, action, before, after, error }`
 * state shape regardless of caller so the UX stays identical across surfaces.
 */
export function CoauthorResultPopover({
  open,
  loading,
  action,
  before,
  after,
  error,
  changes,
  applyLabel,
  onApply,
  onCopy,
  onDiscard,
}: CoauthorResultPopoverProps) {
  const dialogRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    if (!open) return
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        e.preventDefault()
        onDiscard()
      }
    }
    document.addEventListener('keydown', onKey)
    return () => document.removeEventListener('keydown', onKey)
  }, [open, onDiscard])

  useEffect(() => {
    if (!open) return
    dialogRef.current?.focus()
  }, [open])

  if (!open) return null

  const applyDisabled = loading || !!error || after.length === 0
  const copyDisabled = loading || !!error || after.length === 0

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 px-4"
      role="presentation"
      onClick={onDiscard}
    >
      <div
        ref={dialogRef}
        role="dialog"
        aria-modal="true"
        aria-label={`AI ${coauthorActionLabel(action)} result`}
        tabIndex={-1}
        onClick={(e) => e.stopPropagation()}
        className="bg-card w-full max-w-2xl rounded-lg shadow-2xl outline-none"
      >
        <div className="border-border flex items-center justify-between border-b px-4 py-3">
          <div className="text-foreground flex items-center gap-2 text-sm font-medium">
            <Sparkles className="text-primary h-4 w-4" aria-hidden />
            <span>AI {coauthorActionLabel(action)}</span>
            {loading && (
              <Loader2
                className="text-muted-foreground ml-1 h-4 w-4 animate-spin"
                aria-label="Loading"
              />
            )}
          </div>
          <button
            type="button"
            onClick={onDiscard}
            className="text-muted-foreground hover:bg-accent hover:text-muted-foreground rounded p-1"
            aria-label="Close"
          >
            <X className="h-4 w-4" />
          </button>
        </div>

        <div className="grid grid-cols-2 gap-4 p-4">
          <section aria-labelledby="coauthor-before">
            <h3
              id="coauthor-before"
              className="text-muted-foreground mb-2 text-xs font-medium tracking-wide uppercase"
            >
              Before
            </h3>
            <pre className="border-border bg-muted text-foreground max-h-72 overflow-auto rounded border p-3 text-sm whitespace-pre-wrap">
              {before}
            </pre>
          </section>
          <section aria-labelledby="coauthor-after">
            <h3
              id="coauthor-after"
              className="text-muted-foreground mb-2 text-xs font-medium tracking-wide uppercase"
            >
              After
            </h3>
            {loading ? (
              <div
                className="border-border bg-muted text-muted-foreground flex h-72 items-center justify-center rounded border border-dashed text-sm"
                role="status"
              >
                Thinking…
              </div>
            ) : error ? (
              <div className="border-destructive/30 bg-destructive/10 text-destructive flex h-72 items-center justify-center rounded border border-dashed p-3 text-sm">
                {error}
              </div>
            ) : (
              <pre className="border-info/30 bg-info/10 text-foreground max-h-72 overflow-auto rounded border p-3 text-sm whitespace-pre-wrap">
                {after}
              </pre>
            )}
          </section>
        </div>

        {changes && changes.length > 0 && !loading && !error && (
          <div className="border-border border-t px-4 py-3">
            <h3 className="text-muted-foreground mb-2 text-xs font-medium tracking-wide uppercase">
              Changes ({changes.length})
            </h3>
            <ul className="max-h-32 space-y-1 overflow-auto text-xs">
              {changes.map((change, i) => (
                <li key={i} className="bg-muted flex items-start gap-2 rounded px-2 py-1">
                  <span className="text-destructive line-through">{change.original}</span>
                  <span className="text-muted-foreground">→</span>
                  <span className="text-success">{change.corrected}</span>
                  {change.reason && (
                    <span className="text-muted-foreground ml-auto italic">{change.reason}</span>
                  )}
                </li>
              ))}
            </ul>
          </div>
        )}

        <div className="border-border bg-muted flex items-center justify-end gap-2 border-t px-4 py-3">
          <button
            type="button"
            onClick={onDiscard}
            className="border-border bg-card text-foreground hover:bg-accent rounded-md border px-3 py-1.5 text-sm"
          >
            <X className="mr-1.5 inline h-3.5 w-3.5" aria-hidden />
            Discard
          </button>
          <button
            type="button"
            onClick={onCopy}
            disabled={copyDisabled}
            className="border-border bg-card text-foreground hover:bg-accent rounded-md border px-3 py-1.5 text-sm disabled:cursor-not-allowed disabled:opacity-50"
          >
            <Copy className="mr-1.5 inline h-3.5 w-3.5" aria-hidden />
            Copy
          </button>
          <button
            type="button"
            onClick={onApply}
            disabled={applyDisabled}
            className="bg-primary hover:bg-primary/90 rounded-md px-3 py-1.5 text-sm font-medium text-white disabled:cursor-not-allowed disabled:opacity-50"
          >
            <Check className="mr-1.5 inline h-3.5 w-3.5" aria-hidden />
            {applyLabel ?? 'Apply'}
          </button>
        </div>
      </div>
    </div>
  )
}
