"use client";

import { useState } from "react";
import { Loader2 } from "lucide-react";

import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";

/**
 * Per-paper confidentiality agreement modal gating the reviewer download
 * path. Contract per Phase 2B-ii §4.1. The body text is verbatim from
 * the saved 2B-ii design — the GDPR/DPDP disclosure and email-watermark
 * notice (Decision D10) must not be paraphrased.
 *
 * <p>State ownership follows the saved design: the <b>parent</b> owns
 * {@code isOpen} and the API call. The modal awaits
 * {@link onAccept} (a Promise) and surfaces any rejection inline
 * without closing. This prevents the double-close-flash pattern where
 * the modal unmounts mid-promise and makes cancel/retry/error flows
 * deterministic.
 */
export interface ConfidentialityAgreementModalProps {
  isOpen: boolean;
  /** Reference number shown in the title, e.g. "Agreement — SSJ-2026-00042". */
  paperReferenceNo: string;
  /**
   * Called when the user clicks "I Agree & Download". The parent is
   * expected to (1) call {@code reviewerPaperApi.acceptAgreement},
   * (2) close the modal by flipping {@code isOpen}, and (3) trigger
   * the download. Any thrown / rejected error is caught by the modal
   * and surfaced as an inline error — the modal stays open.
   */
  onAccept: () => Promise<void>;
  /** Called when the user clicks Cancel, presses Esc, or backdrop-clicks. */
  onCancel: () => void;
}

export function ConfidentialityAgreementModal({
  isOpen,
  paperReferenceNo,
  onAccept,
  onCancel,
}: ConfidentialityAgreementModalProps) {
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleAccept() {
    setSubmitting(true);
    setError(null);
    try {
      await onAccept();
      // Parent owns close via isOpen flip. Do not close here.
    } catch (e) {
      const msg =
        (e as { response?: { data?: { message?: string } }; message?: string })
          ?.response?.data?.message ??
        (e as { message?: string })?.message ??
        "Failed to record your acceptance. Please try again.";
      setError(msg);
      setSubmitting(false);
    }
  }

  function handleOpenChange(next: boolean) {
    // Radix fires onOpenChange(false) on backdrop click / Esc. Route
    // that through the cancel path so the parent can react. Ignore
    // open-true transitions (the parent is the single source of truth).
    if (!next && !submitting) {
      setError(null);
      onCancel();
    }
  }

  return (
    <Dialog open={isOpen} onOpenChange={handleOpenChange}>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle>Agreement — {paperReferenceNo}</DialogTitle>
          <DialogDescription>
            Before you can download this paper, please read and accept the following:
          </DialogDescription>
        </DialogHeader>

        <div className="max-h-[60vh] space-y-4 overflow-y-auto text-sm text-gray-700">
          <p className="font-semibold text-gray-900">Confidentiality &amp; Ethics Agreement</p>

          <p>By downloading this paper, you agree to:</p>

          <ol className="list-decimal space-y-3 pl-5">
            <li>
              <strong>Use the content solely for the purpose of peer review.</strong> You
              will not use any part of this paper — text, data, methodology, findings, or
              ideas — for personal benefit, third-party benefit, or any purpose beyond
              your assigned review.
            </li>
            <li>
              <strong>Not share or distribute this paper.</strong> You will not forward,
              upload, share, post, or republish this paper or any portion of it, in any
              form, to anyone, including colleagues, students, or institutional
              repositories.
            </li>
            <li>
              <strong>Maintain confidentiality of the submission and its authors.</strong>{" "}
              You will not discuss the existence, content, or status of this submission
              outside of the review process.
            </li>
            <li>
              <strong>Delete all local copies after completing your review.</strong> Once
              your review is submitted and final, you will delete every local copy of
              this paper from every device under your control.
            </li>
          </ol>

          <div className="rounded-md border border-amber-200 bg-amber-50 p-3">
            <p className="font-semibold text-amber-900">
              Notice — Your email address is embedded in every download.
            </p>
            <p className="mt-1 text-amber-900">
              Every PDF you download will be watermarked with your email address and the
              download date. This is used to trace leaked or shared copies back to their
              source. By proceeding, you understand that any copy of this paper that
              leaves your control will identify you as the source.
            </p>
          </div>

          <p>
            If you do not accept these terms, click <strong>Cancel</strong> and the
            download will not proceed. If you cannot accept the email-watermark
            disclosure for personal, professional, or institutional reasons, please
            contact the editor to discuss alternative arrangements or reassignment of
            this review.
          </p>
        </div>

        {error ? (
          <p role="alert" className="text-sm text-red-600">
            {error}
          </p>
        ) : null}

        <DialogFooter>
          <button
            type="button"
            onClick={() => {
              if (!submitting) {
                setError(null);
                onCancel();
              }
            }}
            disabled={submitting}
            className="inline-flex items-center justify-center rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 shadow-sm hover:bg-gray-50 disabled:opacity-50"
          >
            Cancel
          </button>
          <button
            type="button"
            onClick={handleAccept}
            disabled={submitting}
            className="inline-flex items-center justify-center gap-2 rounded-md bg-indigo-600 px-4 py-2 text-sm font-semibold text-white shadow hover:bg-indigo-700 disabled:opacity-50"
          >
            {submitting ? (
              <>
                <Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" />
                Recording…
              </>
            ) : (
              "I Agree & Download"
            )}
          </button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

export default ConfidentialityAgreementModal;
