// Set Password modal — shown when URL has ?open_modal=set-password&verification_key=<key>
const { useState: useSP } = React;

function SetPassword({ verificationKey, onClose }) {
  const [password, setPassword] = useSP("");
  const [confirm,  setConfirm]  = useSP("");
  const [showPass, setShowPass] = useSP(false);
  const [showConf, setShowConf] = useSP(false);
  const [errors,   setErrors]   = useSP({});
  const [loading,  setLoading]  = useSP(false);
  const [success,  setSuccess]  = useSP(false);

  function clearErr(k) { setErrors((e) => ({ ...e, [k]: null })); }

  async function submit(e) {
    e.preventDefault();
    const errs = {};
    if (!password.trim())          errs.password = "Password is required.";
    else if (password.length < 8)  errs.password = "Password must be at least 8 characters.";
    if (!confirm.trim())           errs.confirm  = "Please confirm your password.";
    else if (password !== confirm) errs.confirm  = "Passwords do not match.";
    if (Object.keys(errs).length) { setErrors(errs); return; }

    setErrors({});
    setLoading(true);
    try {
      const r = await window.api.setPassword(verificationKey, password);
      if (r?.status === "success") {
        setSuccess(true);
        setTimeout(onClose, 2000);
        return;
      }
      const data = r?.data;
      if (data && typeof data === "object") {
        const fe = {};
        if (data.password)         fe.password = Array.isArray(data.password)         ? data.password[0]         : data.password;
        if (data.verification_key) fe._general  = Array.isArray(data.verification_key) ? data.verification_key[0] : data.verification_key;
        if (Object.keys(fe).length) { setErrors(fe); return; }
      }
      setErrors({ _general: typeof data === "string" ? data : "Failed to set password. The link may have expired." });
    } catch (_) {
      setErrors({ _general: "Could not reach the server. Try again." });
    } finally {
      setLoading(false);
    }
  }

  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 300, display: "grid", placeItems: "center", padding: 24 }}>
      <div style={{ position: "absolute", inset: 0, background: "#10162e99", backdropFilter: "blur(6px)" }} />
      <div className="fade-up" style={{
        position: "relative", width: "100%", maxWidth: 420,
        background: "var(--bg-app)", borderRadius: 16,
        boxShadow: "0 24px 80px #10162e44", padding: "36px 36px 32px"
      }}>
        <div style={{ marginBottom: 24 }}>
          <div style={{
            width: 44, height: 44, borderRadius: 12, background: "#EEF2FF",
            display: "grid", placeItems: "center", marginBottom: 16
          }}>
            <Icon name="lock" size={20} style={{ color: "#4F46E5" }} />
          </div>
          <h2 style={{ fontSize: 22, fontWeight: 800, margin: "0 0 6px", color: "var(--navy)", letterSpacing: "-.01em" }}>
            Set your password
          </h2>
          <p style={{ margin: 0, color: "var(--muted)", fontSize: 14 }}>
            Choose a strong password to secure your account.
          </p>
        </div>

        {success ? (
          <div style={{ textAlign: "center", padding: "16px 0" }}>
            <div style={{
              width: 52, height: 52, borderRadius: "50%", background: "#ECFDF5",
              display: "grid", placeItems: "center", margin: "0 auto 14px"
            }}>
              <Icon name="check" size={24} style={{ color: "#059669" }} />
            </div>
            <p style={{ fontWeight: 700, color: "var(--navy)", margin: "0 0 6px" }}>Password set!</p>
            <p style={{ color: "var(--muted)", fontSize: 13.5, margin: 0 }}>Redirecting to login…</p>
          </div>
        ) : (
          <form onSubmit={submit} style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            {errors._general && (
              <div style={{
                padding: "10px 14px", background: "#FEF2F2", border: "1px solid #FEE2E2",
                borderRadius: 8, fontSize: 13.5, color: "#DC2626"
              }}>
                {errors._general}
              </div>
            )}
            <Field label="New password" error={errors.password}>
              <div style={{ position: "relative" }}>
                <input
                  className={"input" + (errors.password ? " err" : "")}
                  type={showPass ? "text" : "password"}
                  value={password}
                  onChange={(e) => { setPassword(e.target.value); clearErr("password"); }}
                  placeholder="Min. 8 characters"
                  autoComplete="new-password"
                  style={{ paddingRight: 44 }}
                />
                <button type="button" onClick={() => setShowPass((v) => !v)} aria-label="Toggle password"
                  style={{
                    position: "absolute", right: 6, top: 6, width: 32, height: 32,
                    borderRadius: 8, border: "none", background: "transparent",
                    color: "var(--muted)", cursor: "pointer", display: "grid", placeItems: "center"
                  }}>
                  <Icon name="eye" size={17} />
                </button>
              </div>
            </Field>
            <Field label="Confirm password" error={errors.confirm}>
              <div style={{ position: "relative" }}>
                <input
                  className={"input" + (errors.confirm ? " err" : "")}
                  type={showConf ? "text" : "password"}
                  value={confirm}
                  onChange={(e) => { setConfirm(e.target.value); clearErr("confirm"); }}
                  placeholder="Re-enter password"
                  autoComplete="new-password"
                  style={{ paddingRight: 44 }}
                />
                <button type="button" onClick={() => setShowConf((v) => !v)} aria-label="Toggle confirm"
                  style={{
                    position: "absolute", right: 6, top: 6, width: 32, height: 32,
                    borderRadius: 8, border: "none", background: "transparent",
                    color: "var(--muted)", cursor: "pointer", display: "grid", placeItems: "center"
                  }}>
                  <Icon name="eye" size={17} />
                </button>
              </div>
            </Field>
            <button className="btn btn-navy" type="submit" disabled={loading} style={{ height: 46, marginTop: 4 }}>
              {loading ? "Setting password…" : <>Set password <Icon name="arrowRight" size={17} /></>}
            </button>
          </form>
        )}
      </div>
    </div>
  );
}

window.SetPassword = SetPassword;
