import type { SourceAnchor } from '@learnitive/latex-source';
import { Button } from '@learnitive/ui-components';
import React from 'react';

export type ReviewCommentTarget = {
  scope: 'anchor' | 'document' | 'project';
  anchor?: SourceAnchor;
  selectedText?: string;
};

export function ReviewCommentDialog({
  open,
  target,
  onClose,
  onSubmit,
}: {
  open: boolean;
  target?: ReviewCommentTarget;
  onClose: () => void;
  onSubmit: (body: string) => Promise<void> | void;
}) {
  const [body, setBody] = React.useState('');
  const [busy, setBusy] = React.useState(false);

  React.useEffect(() => {
    if (open) setBody('');
  }, [open, target]);

  if (!open || !target) return null;
  const title = target.scope === 'project' ? 'Project comment' : target.scope === 'document' ? 'Document comment' : 'Add comment';

  return (
    <div className="fixed inset-0 z-[130] flex items-center justify-center p-4">
      <button
        type="button"
        className="absolute inset-0 cursor-default bg-black/35"
        aria-label="Close review comment dialog"
        onClick={onClose}
      />
      <div className="relative z-10 w-full max-w-lg rounded-lg border bg-background p-4 shadow-xl" role="dialog" aria-modal="true" aria-label={title}>
        <div className="mb-3">
          <h2 className="font-semibold">{title}</h2>
          {target.selectedText && <p className="mt-1 max-h-20 overflow-auto rounded bg-muted/40 px-2 py-1.5 text-xs text-muted-foreground">{target.selectedText}</p>}
        </div>
        <textarea
          autoFocus
          className="min-h-28 w-full resize-y rounded-md border bg-background px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"
          placeholder="Write a review comment…"
          value={body}
          onChange={(event) => setBody(event.currentTarget.value)}
        />
        <div className="mt-3 flex justify-end gap-2">
          <Button variant="outline" onClick={onClose} disabled={busy}>Cancel</Button>
          <Button
            disabled={busy || !body.trim()}
            onClick={async () => {
              setBusy(true);
              try {
                await onSubmit(body.trim());
                onClose();
              } finally {
                setBusy(false);
              }
            }}
          >
            Add comment
          </Button>
        </div>
      </div>
    </div>
  );
}
