const { useState: usePL } = React;

function PortalLogin(props) {
  const { onAuthed } = props || {};
  const [mode, setMode] = usePL("login");
  const [fullName, setFullName] = usePL("");
  const [email, setEmail] = usePL("");
  const [phone, setPhone] = usePL("");
  const [city, setCity] = usePL("");
  const [password, setPassword] = usePL("");
  const [pending, setPending] = usePL(false);
  const [error, setError] = usePL("");
  const [notice, setNotice] = usePL("");

  function PENDING_MSG() {
    return window.getLang() === "en"
      ? "Account created — it is pending admin approval; we'll activate it soon."
      : "تم إنشاء حسابك بنجاح — حسابك قيد مراجعة الإدارة، وسنفعّله قريباً.";
  }

  function mapErr(e) {
    const m = (e && e.message) || "";
    if (/not.?active|account_not_active|pending/i.test(m)) {
      return window.getLang() === "en"
        ? "Your account is pending admin approval."
        : "حسابك قيد المراجعة من الإدارة، لا يمكنك الدخول بعد.";
    }
    return m || (window.getLang() === "en" ? "Something went wrong" : "حدث خطأ ما");
  }

  function switchMode(next) {
    setError("");
    setNotice("");
    setMode(next);
  }

  async function doLogin(ev) {
    ev.preventDefault();
    if (pending) return;
    setError("");
    setNotice("");
    setPending(true);
    try {
      await window.API.login(email, password);
      if (typeof onAuthed === "function") onAuthed();
    } catch (e) {
      setError(mapErr(e));
    } finally {
      setPending(false);
    }
  }

  async function doRegister(ev) {
    ev.preventDefault();
    if (pending) return;
    setError("");
    setNotice("");
    setPending(true);
    try {
      await window.API.register({ fullName, email, phone, city, password });
      if (window.API.hasToken && window.API.hasToken()) {
        if (typeof onAuthed === "function") onAuthed();
      } else {
        setMode("login");
        setNotice(PENDING_MSG());
      }
    } catch (e) {
      setError(mapErr(e));
    } finally {
      setPending(false);
    }
  }

  function toggleLang() {
    window.setLang(window.getLang() === "ar" ? "en" : "ar");
  }

  const langBtnStyle = {
    justifySelf: "end",
  };

  return (
    <div
      style={{
        display: "grid",
        placeItems: "center",
        minHeight: "100vh",
        background: "var(--bg)",
        padding: "24px",
      }}
    >
      <div className="card card-pad" style={{ width: "100%", maxWidth: "400px" }}>
        <div style={{ display: "flex", justifyContent: "flex-end" }}>
          <button
            type="button"
            className="btn btn-ghost btn-sm"
            onClick={toggleLang}
            style={langBtnStyle}
          >
            {window.T("langToggle")}
          </button>
        </div>

        <div className="brand" style={{ marginTop: "8px" }}>
          <span className="brand-mark">{window.Icon ? window.Icon("spark") : null}</span>
          <span className="brand-name">{window.T("brand")}</span>
          <span className="brand-tag">{window.T("portalTag")}</span>
        </div>

        {notice ? (
          <div
            style={{
              border: "1px solid var(--sage-soft)",
              background: "var(--sage-tint)",
              color: "var(--sage-2)",
              borderRadius: "var(--r-md)",
              padding: "12px",
              marginBottom: "12px",
              display: "flex",
              alignItems: "center",
              gap: "8px",
            }}
          >
            <span style={{ display: "inline-flex", alignItems: "center" }}>
              {window.Icon ? window.Icon("check") : null}
            </span>
            <span className="t-tiny">{notice}</span>
          </div>
        ) : null}

        {mode === "login" ? (
          <form onSubmit={doLogin}>
            <div className="serif" style={{ margin: "4px 0 12px" }}>
              {window.T("signIn")}
            </div>

            <label className="t-tiny" style={{ display: "block", marginBottom: "2px" }}>
              {window.T("email")}
            </label>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              autoComplete="username"
              style={{
                border: "1px solid var(--line)",
                borderRadius: "var(--r-sm)",
                padding: "8px 10px",
                width: "100%",
                background: "var(--paper)",
                marginBottom: "8px",
                boxSizing: "border-box",
              }}
            />

            <label className="t-tiny" style={{ display: "block", marginBottom: "2px" }}>
              {window.T("password")}
            </label>
            <input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              autoComplete="current-password"
              style={{
                border: "1px solid var(--line)",
                borderRadius: "var(--r-sm)",
                padding: "8px 10px",
                width: "100%",
                background: "var(--paper)",
                marginBottom: "8px",
                boxSizing: "border-box",
              }}
            />

            <button
              type="submit"
              className="btn btn-primary w-full"
              disabled={pending}
            >
              {pending ? "…" : window.T("signIn")}
            </button>

            {error ? (
              <div className="t-tiny" style={{ color: "var(--danger)", marginTop: "8px" }}>
                {error}
              </div>
            ) : null}

            <div className="flex col center mt-2">
              <button
                type="button"
                className="btn btn-ghost btn-sm"
                onClick={() => switchMode("register")}
              >
                {window.T("noAccount")} {window.T("signUp")}
              </button>
            </div>
          </form>
        ) : (
          <form onSubmit={doRegister}>
            <div className="serif" style={{ margin: "4px 0 12px" }}>
              {window.T("joinTitle")}
            </div>

            <label className="t-tiny" style={{ display: "block", marginBottom: "2px" }}>
              {window.T("fullName")}
            </label>
            <input
              type="text"
              value={fullName}
              onChange={(e) => setFullName(e.target.value)}
              autoComplete="name"
              style={{
                border: "1px solid var(--line)",
                borderRadius: "var(--r-sm)",
                padding: "8px 10px",
                width: "100%",
                background: "var(--paper)",
                marginBottom: "8px",
                boxSizing: "border-box",
              }}
            />

            <label className="t-tiny" style={{ display: "block", marginBottom: "2px" }}>
              {window.T("email")}
            </label>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              autoComplete="email"
              style={{
                border: "1px solid var(--line)",
                borderRadius: "var(--r-sm)",
                padding: "8px 10px",
                width: "100%",
                background: "var(--paper)",
                marginBottom: "8px",
                boxSizing: "border-box",
              }}
            />

            <label className="t-tiny" style={{ display: "block", marginBottom: "2px" }}>
              {window.T("phone")}
            </label>
            <input
              type="tel"
              value={phone}
              onChange={(e) => setPhone(e.target.value)}
              autoComplete="tel"
              style={{
                border: "1px solid var(--line)",
                borderRadius: "var(--r-sm)",
                padding: "8px 10px",
                width: "100%",
                background: "var(--paper)",
                marginBottom: "8px",
                boxSizing: "border-box",
              }}
            />

            <label className="t-tiny" style={{ display: "block", marginBottom: "2px" }}>
              {window.T("city")}
            </label>
            <input
              type="text"
              value={city}
              onChange={(e) => setCity(e.target.value)}
              autoComplete="address-level2"
              style={{
                border: "1px solid var(--line)",
                borderRadius: "var(--r-sm)",
                padding: "8px 10px",
                width: "100%",
                background: "var(--paper)",
                marginBottom: "8px",
                boxSizing: "border-box",
              }}
            />

            <label className="t-tiny" style={{ display: "block", marginBottom: "2px" }}>
              {window.T("password")}
            </label>
            <input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              autoComplete="new-password"
              style={{
                border: "1px solid var(--line)",
                borderRadius: "var(--r-sm)",
                padding: "8px 10px",
                width: "100%",
                background: "var(--paper)",
                marginBottom: "8px",
                boxSizing: "border-box",
              }}
            />

            <button
              type="submit"
              className="btn btn-primary w-full"
              disabled={pending}
            >
              {pending ? "…" : window.T("signUp")}
            </button>

            {error ? (
              <div className="t-tiny" style={{ color: "var(--danger)", marginTop: "8px" }}>
                {error}
              </div>
            ) : null}

            <div className="flex col center mt-2">
              <button
                type="button"
                className="btn btn-ghost btn-sm"
                onClick={() => switchMode("login")}
              >
                {window.T("haveAccount")} {window.T("signIn")}
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

window.PortalLogin = PortalLogin;
