// billing-link.jsx — Settings → Billing tab content for billing-link
// management.
//
// R03 / T0007 (Phase 5). Shows the current Workspace's billing state:
//
//   - If `billing_parent_id` is set: "This Workspace bills via <parent>.
//     Manage subscription / payment methods in <parent>'s billing tab."
//   - If null: "This Workspace pays its own bill" + a "Manage
//     subscription" button that opens Stripe Customer Portal.
//
// Below: a "Use another Workspace's billing" picker that lists every
// Workspace the user is owner/admin of (and that isn't itself billed
// elsewhere — single-level rule from R03 Q2). Selecting one opens a
// confirmation modal which calls `setBillingParent`. A "Use my own
// billing" button calls `unsetBillingParent`.
//
// Exposes window.BillingLinkPane.

(function (window) {
  'use strict';

  const { db, fns, useWorkspace, useAuth } = window.exoteamAuth || {};
  if (!useWorkspace) {
    console.error('billing-link.jsx: window.exoteamAuth missing');
    return;
  }

  function BillingLinkPane({ workspaceId }) {
    const { user } = useAuth();
    const { workspaces, loading: wsLoading } = useWorkspace();
    const [workspace, setWorkspace] = React.useState(null);
    const [parentWorkspace, setParentWorkspace] = React.useState(null);
    const [busy, setBusy] = React.useState(false);
    const [error, setError] = React.useState(null);
    const [picking, setPicking] = React.useState(false);
    const [pendingParent, setPendingParent] = React.useState(null);

    // Live subscription to the current workspace doc — surfaces
    // `billing_parent_id` + `stripe_customer_id` + `tier`.
    React.useEffect(() => {
      if (!workspaceId) return undefined;
      const unsub = db
        .collection('workspaces')
        .doc(workspaceId)
        .onSnapshot(
          (snap) => {
            setWorkspace(snap.exists ? { id: snap.id, ...snap.data() } : null);
          },
          (err) => {
            console.error('BillingLinkPane: workspace snapshot', err);
            setError(err.message || String(err));
          },
        );
      return unsub;
    }, [workspaceId]);

    // Resolve the parent workspace name if billing_parent_id is set.
    React.useEffect(() => {
      if (!workspace || !workspace.billing_parent_id) {
        setParentWorkspace(null);
        return;
      }
      db.collection('workspaces')
        .doc(workspace.billing_parent_id)
        .get()
        .then((snap) => {
          if (snap.exists) setParentWorkspace({ id: snap.id, ...snap.data() });
        })
        .catch((err) =>
          console.error('BillingLinkPane: parent fetch', err),
        );
    }, [workspace && workspace.billing_parent_id]);

    async function openPortal() {
      setBusy(true);
      setError(null);
      try {
        const callable = fns.httpsCallable('createPortalSession');
        const { data } = await callable({
          workspace_id: workspaceId,
          return_url: window.location.origin + window.location.pathname,
        });
        window.location.assign(data.portal_url);
      } catch (err) {
        console.error('createPortalSession failed', err);
        if (err && err.code === 'failed-precondition') {
          setError(
            'No subscription yet. Enable a module in Settings → Modules to start your trial, then upgrade.',
          );
        } else {
          setError(err.message || String(err));
        }
        setBusy(false);
      }
    }

    async function confirmSetParent() {
      if (!pendingParent) return;
      setBusy(true);
      setError(null);
      try {
        const callable = fns.httpsCallable('setBillingParent');
        await callable({
          workspace_id: workspaceId,
          parent_workspace_id: pendingParent.workspace_id,
        });
        setPendingParent(null);
        setPicking(false);
      } catch (err) {
        console.error('setBillingParent failed', err);
        setError(err.message || String(err));
      } finally {
        setBusy(false);
      }
    }

    async function unsetParent() {
      if (
        !window.confirm(
          "Use this Workspace's own billing instead? You'll need to subscribe to modules separately.",
        )
      ) {
        return;
      }
      setBusy(true);
      setError(null);
      try {
        const callable = fns.httpsCallable('unsetBillingParent');
        await callable({ workspace_id: workspaceId });
      } catch (err) {
        console.error('unsetBillingParent failed', err);
        setError(err.message || String(err));
      } finally {
        setBusy(false);
      }
    }

    // Eligible parents: Workspaces the user is owner/admin of, that are
    // NOT the current workspace, and that don't themselves have a
    // billing_parent_id set (single-level rule — enforced server-side
    // too, but we filter the picker to avoid a confusing 400).
    const eligibleParents = (workspaces || []).filter(
      (w) =>
        w.workspace_id !== workspaceId &&
        (w.role === 'owner' || w.role === 'admin') &&
        !w.billing_parent_id,
    );

    const hasParent = !!(workspace && workspace.billing_parent_id);
    const hasStripeCustomer = !!(workspace && workspace.stripe_customer_id);

    if (!workspaceId) {
      return (
        <div>
          <h2 className="exo-admin-title">Billing</h2>
          <p className="exo-admin-subtitle">Pick a workspace to see its billing.</p>
        </div>
      );
    }

    return (
      <div>
        <h2 className="exo-admin-title">Billing</h2>

        {error && (
          <div className="exo-admin-banner is-error" style={{ marginBottom: 14 }}>
            <span>{error}</span>
          </div>
        )}

        {!workspace && <p className="exo-admin-hint">Loading workspace…</p>}

        {workspace && hasParent && (
          <div className="exo-admin-banner is-info" style={{ marginBottom: 18, alignItems: 'flex-start' }}>
            <div>
              <strong>
                Billed via{' '}
                {parentWorkspace
                  ? parentWorkspace.display_name || parentWorkspace.id
                  : workspace.billing_parent_id}
              </strong>
              <p className="exo-admin-hint" style={{ marginTop: 4, marginBottom: 0 }}>
                Subscriptions on this Workspace are managed by the parent.
                Modules subscribed on the parent are accessible here.
              </p>
            </div>
            <button
              type="button"
              className="exo-admin-btn--link is-destructive"
              onClick={unsetParent}
              disabled={busy}
            >
              {busy ? 'Saving…' : "Use this Workspace's own billing"}
            </button>
          </div>
        )}

        {workspace && !hasParent && (
          <>
            <p className="exo-admin-subtitle">
              {hasStripeCustomer
                ? 'This Workspace pays its own bill. Manage payment methods, invoices, and subscriptions in the Stripe Customer Portal.'
                : 'This Workspace pays its own bill. No paid subscription yet — enable a module in Settings → Modules to start your 14-day trial, then upgrade from there.'}
            </p>
            {hasStripeCustomer && (
              <button
                type="button"
                className="exo-admin-btn"
                onClick={openPortal}
                disabled={busy}
                style={{ marginBottom: 18, alignSelf: 'flex-start' }}
              >
                {busy ? 'Opening…' : 'Manage subscription'}
              </button>
            )}
            <hr className="exo-admin-divider" />
            <div>
              <strong>Use another Workspace's billing</strong>
              <p className="exo-admin-hint" style={{ marginTop: 4, marginBottom: 12 }}>
                Pay the bill from another Workspace you own or admin.
                Modules subscribed there will become accessible here.
                Subscriptions on this Workspace will be cancelled — you
                can switch back any time.
              </p>
              {wsLoading && <p className="exo-admin-hint">Loading…</p>}
              {!wsLoading && eligibleParents.length === 0 && (
                <p className="exo-admin-hint">
                  No eligible Workspaces. You need owner or admin role on
                  another Workspace that isn't itself billed elsewhere.
                </p>
              )}
              {!picking && eligibleParents.length > 0 && (
                <button
                  type="button"
                  className="exo-admin-btn--link"
                  onClick={() => setPicking(true)}
                  disabled={busy}
                >
                  Pick a billing-parent Workspace →
                </button>
              )}
              {picking && (
                <ul className="exo-admin-list" style={{ marginTop: 10 }}>
                  {eligibleParents.map((w) => (
                    <li key={w.workspace_id} className="exo-admin-list-row">
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <strong>{w.display_name || w.workspace_id}</strong>
                        <span
                          style={{
                            color: 'var(--exo-ink-tertiary)',
                            fontSize: 12,
                            marginLeft: 8,
                          }}
                        >
                          · {w.role}
                        </span>
                      </div>
                      <button
                        type="button"
                        className="exo-admin-btn--link"
                        onClick={() => setPendingParent(w)}
                        disabled={busy}
                      >
                        Use →
                      </button>
                    </li>
                  ))}
                </ul>
              )}
            </div>
          </>
        )}

        {pendingParent && (
          <ConfirmModal
            title={`Bill via ${pendingParent.display_name || pendingParent.workspace_id}?`}
            body={
              <>
                <p style={{ margin: 0 }}>
                  Subscriptions on this Workspace will be cancelled. Module
                  access will be inherited from{' '}
                  <strong>
                    {pendingParent.display_name || pendingParent.workspace_id}
                  </strong>
                  .
                </p>
                <p style={{ marginTop: 8, marginBottom: 0 }}>
                  You can switch back any time.
                </p>
              </>
            }
            confirmLabel={busy ? 'Saving…' : 'Set billing parent'}
            onConfirm={confirmSetParent}
            onCancel={() => setPendingParent(null)}
            disabled={busy}
          />
        )}
      </div>
    );
  }

  function ConfirmModal({ title, body, confirmLabel, onConfirm, onCancel, disabled }) {
    return (
      <div className="exo-admin-modal-backdrop" onClick={onCancel}>
        <div className="exo-admin-modal" onClick={(e) => e.stopPropagation()}>
          <h3 className="exo-admin-modal-title">{title}</h3>
          <div className="exo-admin-modal-body">{body}</div>
          <div className="exo-admin-modal-actions">
            <button
              type="button"
              className="exo-admin-btn exo-admin-btn--ghost"
              onClick={onCancel}
              disabled={disabled}
            >
              Cancel
            </button>
            <button
              type="button"
              className="exo-admin-btn"
              onClick={onConfirm}
              disabled={disabled}
            >
              {confirmLabel}
            </button>
          </div>
        </div>
      </div>
    );
  }

  window.BillingLinkPane = BillingLinkPane;
})(window);
