"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { useTranslations, useFormatter } from "next-intl";
import { Modal } from "@/components/ui/modal";
import { formatRelative } from "@/lib/format";

interface Props {
  tenantName: string;
  /**
   * Current suspend state — server-derived. Drives which control the
   * customer sees: "Cancel subscription" while active, the
   * resume-request flow while suspended.
   */
  suspended: boolean;
  /**
   * True when the viewer has platform admin role. Platform users are
   * the only ones who can directly resume a tenant via PATCH; owners
   * must go through the resume-request flow. We use this in the
   * suspended branch to decide whether to render a direct "Resume"
   * button or the "Request reactivation" workflow.
   */
  isPlatform: boolean;
  /**
   * If a resume request is currently pending for this tenant, its
   * id, when it was submitted, and the customer's optional note.
   * The component renders an info card with a cancel-request button
   * instead of the request-reactivation button. Only meaningful when
   * `suspended === true`.
   */
  pendingResumeRequest: {
    id: string;
    createdAt: string;
    customerNotes: string | null;
  } | null;
}

/**
 * SubscriptionToggle — owner-side cancel/resume control.
 *
 * Three render states:
 *   1. Active: "Cancel subscription" button + confirmation modal
 *      (mentions 60-day retention before permanent deletion).
 *   2. Suspended, no pending resume request: "Request reactivation"
 *      button + simple confirmation modal explaining admin review.
 *   3. Suspended, pending resume request: status card "Reactivation
 *      requested X days ago" + "Cancel request" button.
 *
 * Platform admins viewing a suspended tenant get a fourth state in
 * place of #2/#3: a direct "Resume now" button (no admin queue, no
 * request flow). This is the admin escape hatch.
 *
 * The control intentionally lives at the bottom of the tenant
 * detail page rather than near the top — putting it next to the
 * status badge would invite mis-clicks.
 */
export function SubscriptionToggle({
  tenantName,
  suspended,
  isPlatform,
  pendingResumeRequest,
}: Props) {
  const t = useTranslations("tenantDetail");
  const tCommon = useTranslations("common");
  const f = useFormatter();
  const router = useRouter();

  const [confirmCancelOpen, setConfirmCancelOpen] = useState(false);
  const [confirmResumeOpen, setConfirmResumeOpen] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");
  // Feature 6: customer's free-form note attached to the resume
  // request. Reset when the modal opens/closes so re-opening doesn't
  // show stale text from a previous abandoned attempt.
  const [resumeNotes, setResumeNotes] = useState("");

  // Customer-side cancel: PATCH suspend=true. Same path as before.
  // The 60-day retention copy in the modal is the new bit (Bug 37b);
  // mechanics are unchanged.
  const cancel = async () => {
    setSubmitting(true);
    setError("");
    try {
      const res = await fetch(
        `/api/tenants/${encodeURIComponent(tenantName)}/suspend`,
        {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ suspend: true }),
        }
      );
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.error || t("subscriptionUpdateFailed"));
      }
      setConfirmCancelOpen(false);
      router.refresh();
    } catch (e: any) {
      setError(e.message);
    } finally {
      setSubmitting(false);
    }
  };

  // Owner-side resume request: POST a 'resume' tenant_request that
  // sits pending until admin acts. Different from cancel: no PATCH
  // on the CR — that happens only when admin approves.
  const requestResume = async () => {
    setSubmitting(true);
    setError("");
    try {
      const res = await fetch(
        `/api/tenants/${encodeURIComponent(tenantName)}/resume-request`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            // Trim and omit on empty so the API stores NULL rather
            // than empty string. The endpoint's zod transform also
            // handles this; double-checking on the client lets us
            // skip the round-trip when there's nothing to send.
            customerNotes: resumeNotes.trim() || undefined,
          }),
        }
      );
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.error || t("subscriptionUpdateFailed"));
      }
      setConfirmResumeOpen(false);
      setResumeNotes("");
      router.refresh();
    } catch (e: any) {
      setError(e.message);
    } finally {
      setSubmitting(false);
    }
  };

  // Customer cancels their own pending resume request.
  const cancelResumeRequest = async () => {
    if (!pendingResumeRequest) return;
    setSubmitting(true);
    setError("");
    try {
      const res = await fetch(
        `/api/onboarding/${pendingResumeRequest.id}`,
        { method: "DELETE" }
      );
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.error || t("subscriptionUpdateFailed"));
      }
      router.refresh();
    } catch (e: any) {
      setError(e.message);
    } finally {
      setSubmitting(false);
    }
  };

  // Platform admin: direct resume, bypassing the request flow.
  const adminResume = async () => {
    setSubmitting(true);
    setError("");
    try {
      const res = await fetch(
        `/api/tenants/${encodeURIComponent(tenantName)}/suspend`,
        {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ suspend: false }),
        }
      );
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.error || t("subscriptionUpdateFailed"));
      }
      router.refresh();
    } catch (e: any) {
      setError(e.message);
    } finally {
      setSubmitting(false);
    }
  };

  // ─── Suspended branch ───────────────────────────────────────────────

  if (suspended) {
    // Platform admin sees direct resume. Independent of pending
    // resume — admin can always resume immediately.
    if (isPlatform) {
      return (
        <div>
          <button
            type="button"
            onClick={adminResume}
            disabled={submitting}
            className="text-sm font-medium px-4 py-2 rounded-lg border border-success/30 text-success hover:bg-success/10 transition-colors disabled:opacity-50"
          >
            {submitting
              ? tCommon("loading")
              : t("resumeSubscription")}
          </button>
          {pendingResumeRequest && (
            <p className="text-xs text-text-muted mt-2">
              {t("resumeRequestPendingNoteAdmin")}
            </p>
          )}
          {error && <p className="text-xs text-red-400 mt-2">{error}</p>}
        </div>
      );
    }

    // Owner with pending resume request: render the request status
    // card with cancel.
    if (pendingResumeRequest) {
      return (
        <div>
          <div className="rounded-xl border border-amber-500/30 bg-amber-500/5 px-4 py-3">
            <div className="text-sm font-medium text-amber-400 mb-1">
              {t("resumeRequestPendingTitle")}
            </div>
            <div className="text-xs text-text-secondary">
              {t("resumeRequestPendingDescription", {
                when: formatRelative(pendingResumeRequest.createdAt, f),
              })}
            </div>
            {/* Feature 6: echo the customer's note back so they can
                see what they wrote. Useful especially when they
                later wonder "what did I tell them?" or want to
                confirm before cancelling and resubmitting. */}
            {pendingResumeRequest.customerNotes && (
              <div className="mt-2 text-xs text-text-secondary border-l-2 border-amber-500/30 pl-3 whitespace-pre-wrap">
                {pendingResumeRequest.customerNotes}
              </div>
            )}
            <button
              type="button"
              onClick={cancelResumeRequest}
              disabled={submitting}
              className="mt-3 text-xs px-3 py-1.5 rounded-lg border border-border text-text-secondary hover:text-text-primary transition-colors disabled:opacity-50"
            >
              {submitting
                ? tCommon("loading")
                : t("cancelResumeRequest")}
            </button>
          </div>
          {error && <p className="text-xs text-red-400 mt-2">{error}</p>}
        </div>
      );
    }

    // Owner with no pending request: offer to create one.
    return (
      <div>
        <button
          type="button"
          onClick={() => setConfirmResumeOpen(true)}
          className="text-sm font-medium px-4 py-2 rounded-lg border border-success/30 text-success hover:bg-success/10 transition-colors"
        >
          {t("requestReactivation")}
        </button>
        {error && !confirmResumeOpen && (
          <p className="text-xs text-red-400 mt-2">{error}</p>
        )}

        {confirmResumeOpen && (
          <Modal
            open={confirmResumeOpen}
            onClose={() => setConfirmResumeOpen(false)}
            ariaLabel={t("requestReactivationConfirmTitle")}
          >
            <h3 className="font-display text-lg font-semibold text-text-primary mb-2">
              {t("requestReactivationConfirmTitle")}
            </h3>
            <p className="text-sm text-text-secondary mb-4">
              {t("requestReactivationConfirmDescription")}
            </p>

            {/* Feature 6: optional explanatory note. Useful for
                customers to tell admin why they want reactivation
                — e.g. "we paused over winter break, picking back
                up". Stored on the tenant_request and surfaced in
                the admin queue. */}
            <div className="mb-5">
              <label className="block text-xs uppercase tracking-wider text-text-muted mb-1.5">
                {t("requestReactivationNoteLabel")}{" "}
                <span className="text-text-muted normal-case">
                  ({tCommon("optional")})
                </span>
              </label>
              <textarea
                value={resumeNotes}
                onChange={(e) => setResumeNotes(e.target.value)}
                rows={3}
                maxLength={2000}
                placeholder={t("requestReactivationNotePlaceholder")}
                disabled={submitting}
                className="w-full px-3 py-2 rounded-lg border border-border bg-surface-2 text-text-primary text-sm focus:outline-none focus:border-text-secondary disabled:opacity-50"
              />
            </div>

            {error && (
              <div className="text-xs text-red-400 bg-red-400/10 border border-red-400/20 rounded-lg px-3 py-2 mb-3">
                {error}
              </div>
            )}

            <div className="flex justify-end gap-2">
              <button
                type="button"
                onClick={() => setConfirmResumeOpen(false)}
                disabled={submitting}
                className="text-sm px-4 py-2 rounded-lg border border-border text-text-secondary hover:text-text-primary transition-colors"
              >
                {tCommon("cancel")}
              </button>
              <button
                type="button"
                onClick={requestResume}
                disabled={submitting}
                className="text-sm px-4 py-2 rounded-lg bg-success text-white hover:bg-success/90 transition-colors disabled:opacity-50"
              >
                {submitting
                  ? tCommon("loading")
                  : t("requestReactivationConfirm")}
              </button>
            </div>
          </Modal>
        )}
      </div>
    );
  }

  // ─── Active branch ──────────────────────────────────────────────────

  return (
    <div>
      <button
        type="button"
        onClick={() => setConfirmCancelOpen(true)}
        className="text-sm font-medium px-4 py-2 rounded-lg border border-border text-text-secondary hover:text-text-primary hover:border-text-secondary transition-colors"
      >
        {t("cancelSubscription")}
      </button>
      {error && !confirmCancelOpen && (
        <p className="text-xs text-red-400 mt-2">{error}</p>
      )}

      {confirmCancelOpen && (
        <Modal
          open={confirmCancelOpen}
          onClose={() => setConfirmCancelOpen(false)}
          ariaLabel={t("cancelConfirmTitle")}
        >
          <h3 className="font-display text-lg font-semibold text-text-primary mb-2">
            {t("cancelConfirmTitle")}
          </h3>
          <p className="text-sm text-text-secondary mb-3">
            {t("cancelConfirmDescription")}
          </p>
          <ul className="text-xs text-text-muted list-disc list-inside space-y-1 mb-3">
            <li>{t("cancelConfirmBullet1")}</li>
            <li>{t("cancelConfirmBullet2")}</li>
            <li>{t("cancelConfirmBullet3")}</li>
          </ul>
          {/* Bug 37b: 60-day retention warning. Distinct paragraph so it
              reads as a separate, more serious commitment than the
              regular bullets above. */}
          <div className="text-xs text-amber-400 bg-amber-400/10 border border-amber-400/20 rounded-lg px-3 py-2 mb-5">
            {t("cancelConfirmRetentionWarning")}
          </div>

          {error && (
            <div className="text-xs text-red-400 bg-red-400/10 border border-red-400/20 rounded-lg px-3 py-2 mb-3">
              {error}
            </div>
          )}

          <div className="flex justify-end gap-2">
            <button
              type="button"
              onClick={() => setConfirmCancelOpen(false)}
              disabled={submitting}
              className="text-sm px-4 py-2 rounded-lg border border-border text-text-secondary hover:text-text-primary transition-colors"
            >
              {tCommon("cancel")}
            </button>
            <button
              type="button"
              onClick={cancel}
              disabled={submitting}
              className="text-sm px-4 py-2 rounded-lg bg-amber-500 text-white hover:bg-amber-600 transition-colors disabled:opacity-50"
            >
              {submitting
                ? tCommon("loading")
                : t("cancelSubscriptionConfirm")}
            </button>
          </div>
        </Modal>
      )}
    </div>
  );
}
