// Bot auth wizard: multi-step flow — Select Bot → Request Code → OTP → 2FA → Done.
// Connects to real Telegram auth API endpoints.

const { useState, useRef } = React;

const STEPS = [
  { id: "select",  label: "Select Bot" },
  { id: "request", label: "Send Code" },
  { id: "otp",     label: "Enter OTP" },
  { id: "twofa",   label: "2FA" },
  { id: "done",    label: "Done" },
];

// ─── Step progress indicator ─────────────────────────────────────────────
const Stepper = ({ currentStep, doneSteps }) => (
  <div className="stepper">
    {STEPS.map((s, i) => {
      const isDone = doneSteps.includes(s.id);
      const isActive = currentStep === s.id;
      return (
        <React.Fragment key={s.id}>
          <div className={`step ${isActive ? "active" : ""} ${isDone ? "done" : ""}`}>
            <span className="step-num">
              {isDone ? <I.Check size={12} /> : i + 1}
            </span>
            <span>{s.label}</span>
          </div>
          {i < STEPS.length - 1 && <div className="step-bar" />}
        </React.Fragment>
      );
    })}
  </div>
);

// ─── Step: Select bot ────────────────────────────────────────────────────
const StepSelect = ({ selectedBotId, onSelect, preselectedBotId }) => {
  const { data: bots, loading } = useApi(BotApi.list, []);
  const needsAuth = (bots || []).filter((b) =>
    ["auth_required", "paused", "error", "active"].includes(b.status)
  );

  // Pre-select if coming from bot detail "re-auth"
  const effectiveSelected = selectedBotId || preselectedBotId || "";

  return (
    <div>
      <h3 style={{ fontSize: 14, margin: "4px 0 6px", fontWeight: 600 }}>Select a bot to authenticate</h3>
      <p className="muted" style={{ fontSize: 13, marginTop: 0, marginBottom: 16 }}>
        Choose the Telegram account you want to authenticate.
      </p>
      {loading ? (
        <div className="muted" style={{ fontSize: 13 }}>Loading bots…</div>
      ) : needsAuth.length === 0 ? (
        <Empty icon={I.Bot} title="No bots available" sub="Add a bot first before authenticating." />
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {needsAuth.map((b) => (
            <div
              key={b._id}
              onClick={() => onSelect(b._id)}
              style={{
                display: "flex", alignItems: "center", gap: 12,
                padding: "12px 14px",
                border: `1px solid ${effectiveSelected === b._id ? "var(--accent)" : "var(--border)"}`,
                background: effectiveSelected === b._id ? "var(--accent-bg)" : "var(--bg-card-2)",
                borderRadius: 8, cursor: "pointer", transition: "all .12s",
              }}
            >
              <Avatar name={b.name} size="lg" />
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 500 }}>{b.name}</div>
                <div className="mono muted" style={{ fontSize: 11.5 }}>{b.phone}</div>
              </div>
              <PlatformChip platform={b.platform} />
              <StatusBadge status={b.status} />
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

// ─── Step: Request OTP code ──────────────────────────────────────────────
const StepRequest = ({ botId, onSuccess, onError }) => {
  const [loading, setLoading] = useState(false);
  const { data: bots } = useApi(BotApi.list, []);
  const bot = (bots || []).find((b) => b._id === botId);

  const handleRequest = async () => {
    setLoading(true);
    try {
      await BotApi.requestCode(botId);
      onSuccess();
    } catch (e) {
      onError(e.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <h3 style={{ fontSize: 14, margin: "4px 0 6px", fontWeight: 600 }}>Send verification code</h3>
      <p className="muted" style={{ fontSize: 13, marginTop: 0, marginBottom: 16 }}>
        We'll send a Telegram OTP to <span className="mono" style={{ color: "var(--fg)" }}>{bot?.phone || "…"}</span>.
      </p>
      {bot && (
        <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 14px", background: "var(--bg-card-2)", border: "1px solid var(--border)", borderRadius: 8, marginBottom: 16 }}>
          <Avatar name={bot.name} size="lg" />
          <div>
            <div style={{ fontWeight: 500 }}>{bot.name}</div>
            <div className="mono muted" style={{ fontSize: 12 }}>{bot.phone}</div>
          </div>
          <PlatformChip platform={bot.platform} />
        </div>
      )}
      <button className="btn primary" onClick={handleRequest} disabled={loading} style={{ width: "100%", height: 36 }}>
        {loading ? <><span className="spinner"></span> Sending…</> : <><I.Send /> Send Code</>}
      </button>
    </div>
  );
};

// ─── Step: Enter OTP ─────────────────────────────────────────────────────
const StepOtp = ({ botId, onSuccess, onNeed2FA, onError }) => {
  const [otp, setOtp] = useState(["", "", "", "", ""]);
  const [loading, setLoading] = useState(false);
  const refs = useRef([]);

  const handleChange = (i, val) => {
    const digit = val.replace(/\D/g, "").slice(-1);
    const next = [...otp];
    next[i] = digit;
    setOtp(next);
    if (digit && i < 4) refs.current[i + 1]?.focus();
  };

  const handleKeyDown = (i, e) => {
    if (e.key === "Backspace" && !otp[i] && i > 0) refs.current[i - 1]?.focus();
  };

  const handleSubmit = async () => {
    const code = otp.join("");
    if (code.length < 5) return;
    setLoading(true);
    try {
      const res = await BotApi.submitCode(botId, { code });
      // Backend signals 2FA needed via message or status
      if (res.requires_password || res.message?.toLowerCase().includes("password") || res.message?.toLowerCase().includes("2fa")) {
        onNeed2FA();
      } else {
        onSuccess();
      }
    } catch (e) {
      const msg = e.message || "";
      if (msg.toLowerCase().includes("password") || msg.toLowerCase().includes("2fa")) {
        onNeed2FA();
      } else {
        onError(msg);
      }
    } finally {
      setLoading(false);
    }
  };

  const full = otp.every((d) => d !== "");

  return (
    <div>
      <h3 style={{ fontSize: 14, margin: "4px 0 6px", fontWeight: 600 }}>Enter the verification code</h3>
      <p className="muted" style={{ fontSize: 13, marginTop: 0, marginBottom: 4 }}>
        Enter the 5-digit code sent to your Telegram app.
      </p>
      <div className="otp-row">
        {otp.map((v, i) => (
          <input
            key={i}
            ref={(el) => (refs.current[i] = el)}
            className={`otp-cell ${v ? "filled" : ""}`}
            value={v}
            onChange={(e) => handleChange(i, e.target.value)}
            onKeyDown={(e) => handleKeyDown(i, e)}
            maxLength={1}
            inputMode="numeric"
            autoFocus={i === 0}
          />
        ))}
      </div>
      <button
        className="btn primary"
        onClick={handleSubmit}
        disabled={!full || loading}
        style={{ width: "100%", height: 36 }}
      >
        {loading ? <><span className="spinner"></span> Verifying…</> : "Submit Code"}
      </button>
    </div>
  );
};

// ─── Step: 2FA password ──────────────────────────────────────────────────
const Step2FA = ({ botId, onSuccess, onError }) => {
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);

  const handleSubmit = async () => {
    if (!password) return;
    setLoading(true);
    try {
      await BotApi.submitPassword(botId, { password });
      onSuccess();
    } catch (e) {
      onError(e.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <h3 style={{ fontSize: 14, margin: "4px 0 6px", fontWeight: 600, display: "flex", alignItems: "center", gap: 8 }}>
        <I.ShieldCheck size={16} style={{ color: "var(--green)" }} /> Cloud password (2FA)
      </h3>
      <p className="muted" style={{ fontSize: 13, marginTop: 0, marginBottom: 16 }}>
        This account has 2-step verification. Enter the cloud password to finish.
      </p>
      <div className="field">
        <label className="field-label">Password</label>
        <input
          className="input"
          type="password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          onKeyDown={(e) => e.key === "Enter" && handleSubmit()}
          placeholder="••••••••"
          autoFocus
        />
      </div>
      <div style={{ padding: 12, background: "var(--yellow-bg)", borderRadius: 6, display: "flex", gap: 10, marginBottom: 16 }}>
        <I.AlertTriangle size={14} style={{ color: "var(--yellow)", flexShrink: 0, marginTop: 2 }} />
        <div style={{ fontSize: 12, color: "var(--yellow-fg)" }}>
          Cloud passwords are stored securely. Rotate them when staff offboards.
        </div>
      </div>
      <button className="btn primary" onClick={handleSubmit} disabled={!password || loading} style={{ width: "100%", height: 36 }}>
        {loading ? <><span className="spinner"></span> Verifying…</> : "Submit Password"}
      </button>
    </div>
  );
};

// ─── Step: Done ──────────────────────────────────────────────────────────
const StepDone = ({ botId, onGoToBot }) => {
  const { data: bots } = useApi(BotApi.list, []);
  const bot = (bots || []).find((b) => b._id === botId);

  return (
    <div style={{ textAlign: "center", padding: "16px 0 8px" }}>
      <div style={{ width: 56, height: 56, borderRadius: "50%", background: "var(--green-bg)", color: "var(--green)", display: "grid", placeItems: "center", margin: "0 auto 16px" }}>
        <I.Check size={28} />
      </div>
      <h3 style={{ fontSize: 18, margin: "0 0 6px", fontWeight: 600, letterSpacing: "-0.01em" }}>Bot authenticated</h3>
      <p className="muted" style={{ fontSize: 13, marginTop: 0, marginBottom: 20 }}>
        <span className="mono" style={{ color: "var(--fg)" }}>{bot?.phone || "Bot"}</span> is now authenticated and ready.
      </p>
      {bot && (
        <div style={{ display: "inline-flex", flexDirection: "column", gap: 8, textAlign: "left", padding: 14, background: "var(--bg-card-2)", border: "1px solid var(--border)", borderRadius: 8, minWidth: 260 }}>
          <div style={{ display: "flex", justifyContent: "space-between", gap: 16, fontSize: 12.5 }}>
            <span className="muted">Name</span><span style={{ fontWeight: 500 }}>{bot.name}</span>
          </div>
          <div style={{ display: "flex", justifyContent: "space-between", gap: 16, fontSize: 12.5 }}>
            <span className="muted">Phone</span><span className="mono">{bot.phone}</span>
          </div>
          <div style={{ display: "flex", justifyContent: "space-between", gap: 16, fontSize: 12.5 }}>
            <span className="muted">Platform</span><PlatformChip platform={bot.platform} />
          </div>
        </div>
      )}
      <div style={{ marginTop: 20 }}>
        <button className="btn primary" onClick={() => onGoToBot(botId)}>
          <I.ChevronRight /> Go to Bot
        </button>
      </div>
    </div>
  );
};

// ─── Auth wizard main component ──────────────────────────────────────────
const AuthWizard = ({ preselectedBotId, onNavigateToBotDetail, onCancel }) => {
  const toast = useToast();
  const [step, setStep] = useState("select");
  const [doneSteps, setDoneSteps] = useState([]);
  const [selectedBotId, setSelectedBotId] = useState(preselectedBotId || "");
  const [need2FA, setNeed2FA] = useState(false);
  const [errorMsg, setErrorMsg] = useState("");

  const advance = (nextStep, currentStep) => {
    setDoneSteps((prev) => [...prev, currentStep]);
    setStep(nextStep);
    setErrorMsg("");
  };

  const handleError = (msg) => {
    setErrorMsg(msg);
    toast.error(msg);
  };

  // Determine visible steps (skip 2FA if not needed)
  const visibleSteps = need2FA ? STEPS : STEPS.filter((s) => s.id !== "twofa");

  return (
    <div className="page" style={{ maxWidth: 720 }}>
      <div className="page-head">
        <div>
          <h1 className="page-title">Auth & 2FA</h1>
          <div className="page-sub">Authenticate a phone number as a Telegram bot.</div>
        </div>
        <button className="btn ghost" onClick={onCancel}><I.X /> Cancel</button>
      </div>

      <Card>
        <Stepper currentStep={step} doneSteps={doneSteps} />
        <hr className="hr" />

        {errorMsg && (
          <div style={{ padding: "10px 12px", background: "var(--red-bg)", border: "1px solid var(--red)", borderRadius: 6, marginBottom: 16, display: "flex", gap: 8, alignItems: "center" }}>
            <I.AlertTriangle size={14} style={{ color: "var(--red)", flexShrink: 0 }} />
            <span style={{ fontSize: 13, color: "var(--red-fg)" }}>{errorMsg}</span>
          </div>
        )}

        {step === "select" && (
          <StepSelect selectedBotId={selectedBotId} onSelect={setSelectedBotId} preselectedBotId={preselectedBotId} />
        )}
        {step === "request" && (
          <StepRequest
            botId={selectedBotId}
            onSuccess={() => advance("otp", "request")}
            onError={handleError}
          />
        )}
        {step === "otp" && (
          <StepOtp
            botId={selectedBotId}
            onSuccess={() => advance("done", "otp")}
            onNeed2FA={() => { setNeed2FA(true); advance("twofa", "otp"); }}
            onError={handleError}
          />
        )}
        {step === "twofa" && (
          <Step2FA
            botId={selectedBotId}
            onSuccess={() => advance("done", "twofa")}
            onError={handleError}
          />
        )}
        {step === "done" && (
          <StepDone botId={selectedBotId} onGoToBot={onNavigateToBotDetail} />
        )}

        {step !== "done" && <hr className="hr" />}

        {step !== "done" && (
          <div style={{ display: "flex", justifyContent: "space-between" }}>
            <button
              className="btn ghost"
              disabled={step === "select"}
              onClick={() => {
                const idx = visibleSteps.findIndex((s) => s.id === step);
                if (idx > 0) setStep(visibleSteps[idx - 1].id);
              }}
            >
              <I.ChevronLeft /> Back
            </button>
            {step === "select" && (
              <button
                className="btn primary"
                disabled={!selectedBotId}
                onClick={() => advance("request", "select")}
              >
                Continue <I.ChevronRight />
              </button>
            )}
          </div>
        )}
      </Card>
    </div>
  );
};

window.AuthWizard = AuthWizard;
