"use client";

// Request-access modal. Renders inside /access page; controlled by
// parent. Submits to POST /api/pam/request and refreshes the parent
// on success.

import { useEffect, useState } from "react";

export type EligibleRow = {
  role: string;
  policy: {
    approvalMode: "audit" | "manual";
    requiresMfa: boolean;
    maxDurationHours: number;
    defaultDurationHours: number;
    description?: string | null;
  } | null;
  currentlyActive: boolean;
};

export default function RequestModal({
  row,
  open,
  onClose,
  onSuccess,
}: {
  row: EligibleRow | null;
  open: boolean;
  onClose: () => void;
  onSuccess: () => void;
}) {
  const [hours, setHours] = useState(1);
  const [justification, setJustification] = useState("");
  const [mfaToken, setMfaToken] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!open || !row) return;
    setHours(row.policy?.defaultDurationHours ?? 1);
    setJustification("");
    setMfaToken("");
    setError(null);
  }, [open, row]);

  if (!open || !row) return null;

  const policy = row.policy;
  const canSubmit =
    !submitting &&
    justification.trim().length >= 20 &&
    hours > 0 &&
    (!policy?.requiresMfa || /^\d{6}$/.test(mfaToken));

  const submit = async () => {
    if (!policy) return;
    setSubmitting(true);
    setError(null);
    try {
      const r = await fetch("/api/pam/request", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          role: row.role,
          durationHours: hours,
          justification: justification.trim(),
          mfaToken: policy.requiresMfa ? mfaToken : undefined,
        }),
      });
      const j = await r.json().catch(() => ({}));
      if (!r.ok) {
        setError(j.error ? `${j.error}${j.detail ? `: ${j.detail}` : ""}` : `HTTP ${r.status}`);
        return;
      }
      onSuccess();
      onClose();
    } catch (err) {
      setError(String(err));
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div
      className="modal show d-block"
      tabIndex={-1}
      style={{ background: "rgba(0,0,0,.4)" }}
      role="dialog"
      onClick={(e) => e.target === e.currentTarget && onClose()}
    >
      <div className="modal-dialog modal-dialog-centered" role="document">
        <div className="modal-content">
          <div className="modal-header">
            <h5 className="modal-title">
              Request <code>{row.role}</code>
            </h5>
            <button type="button" className="btn-close" aria-label="Close" onClick={onClose} />
          </div>
          <div className="modal-body">
            {policy ? (
              <>
                <div className="mb-3 small text-muted">
                  {policy.description}
                  <div className="mt-1">
                    Approval mode:{" "}
                    <span className={`badge ${policy.approvalMode === "audit" ? "bg-success-subtle text-success-emphasis" : "bg-info-subtle text-info-emphasis"}`}>
                      {policy.approvalMode}
                    </span>{" "}
                    {policy.requiresMfa && (
                      <span className="badge bg-warning-subtle text-warning-emphasis ms-1">
                        MFA required
                      </span>
                    )}
                  </div>
                </div>

                <div className="mb-3">
                  <label htmlFor="pam-duration" className="form-label">
                    Duration: <strong>{hours}h</strong> (max {policy.maxDurationHours}h)
                  </label>
                  <input
                    id="pam-duration"
                    type="range"
                    className="form-range"
                    min={1}
                    max={policy.maxDurationHours}
                    value={hours}
                    onChange={(e) => setHours(parseInt(e.target.value, 10))}
                  />
                </div>

                <div className="mb-3">
                  <label htmlFor="pam-justification" className="form-label">
                    Justification <span className="text-muted small">(min 20 chars)</span>
                  </label>
                  <textarea
                    id="pam-justification"
                    className="form-control"
                    rows={3}
                    maxLength={1000}
                    value={justification}
                    onChange={(e) => setJustification(e.target.value)}
                    placeholder="Why do you need this access right now?"
                  />
                </div>

                {policy.requiresMfa && (
                  <div className="mb-3">
                    <label htmlFor="pam-mfa" className="form-label">
                      One-time code <span className="text-muted small">(6 digits)</span>
                    </label>
                    <input
                      id="pam-mfa"
                      type="text"
                      inputMode="numeric"
                      pattern="\d{6}"
                      maxLength={6}
                      className="form-control"
                      value={mfaToken}
                      onChange={(e) => setMfaToken(e.target.value.replace(/\D/g, ""))}
                    />
                  </div>
                )}

                {error && (
                  <div className="alert alert-danger py-2 mb-0 small">{error}</div>
                )}
              </>
            ) : (
              <div className="alert alert-warning py-2 mb-0 small">
                No policy is configured for <code>{row.role}</code>. Ask an administrator
                to add one before requesting this role.
              </div>
            )}
          </div>
          <div className="modal-footer">
            <button type="button" className="btn btn-outline-secondary" onClick={onClose}>
              Cancel
            </button>
            <button
              type="button"
              className="btn btn-primary"
              disabled={!canSubmit}
              onClick={submit}
            >
              {submitting ? "Requesting…" : policy?.approvalMode === "audit" ? "Request & activate" : "Send for approval"}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
