import { Hono } from "hono";
import { Layout } from "./layout.js";
import type InfoAPI from "../../../types/api/info";
import Config from "../../../config/peas.config.js";
import { Locale } from "../../lib/locale.js";
import Icon from "../../components/iconify.js";
import Help from "../../components/help.js";
import toComponent from "../../lib/toComponent.js";
import Turnstile from "../../components/turnstile.js";
import { getKeys as getTurnstileKeys, isEnabled as TurnstileIsEnabled } from "../../lib/turnstile.js";
import { html } from "hono/html";
import { getCookie } from "hono/cookie";
import { isSignin } from "../../lib/token.js";

const SignUp = new Hono();

SignUp.get("/", async (c) => {
  if (await isSignin(getCookie(c, "token") ?? "")) {
    return c.redirect("/home");
  }
  
  const InfoReq = await fetch(`${Config.server.origin}/api/info`, {
    method: "POST",
    cache: "no-store",
  });
  if (!InfoReq.ok) {
    return c.status(500);
  }
  
  const InfoRes: InfoAPI = await InfoReq.json();
  
  const TurnstileEnabled = await TurnstileIsEnabled();
  
  let TurnstileKeys: Array<string> = [];
  if (TurnstileEnabled) {
    TurnstileKeys = await getTurnstileKeys();
  }
  
  let error = false;
  let errorMsg = "";
  if (c.req.query("error") !== undefined) {
    error = true;
    errorMsg = Locale({ text: `ERR_${c.req.query("error")}` }, c.get("language"));
  }
  
  return c.html(
    <Layout
      title={`${Locale({ text: "Signup" }, c.get("language"))} - ${InfoRes.server.name}`}
      noindex
    >
      <main class="text-center">
        {error && (
          <div
            role="alert"
            class="alert alert-error w-fit m-auto"
          >
            <Icon
              icon="mdi:alert-circle-outline"
              color="#ff0000"
            />
            <span>{errorMsg}</span>
          </div>
        )}
        
        <h1 class={`
          text-3xl
          font-bold
          flex
          items-center
          justify-center
        `}>
          <Icon
            icon="material-symbols:person-add-rounded"
            class="w-4"
          />
          {Locale({ text: "Signup" }, c.get("language"))}
        </h1>
        
        <form
          class={`
            flex
            flex-col
            items-center
            justify-center
          `}
          id="form"
        >
          <div>
            <label class={`
              input
              w-70
              m-3
            `}>
              <span class="label">@</span>
              <input
                type="text"
                placeholder={Locale({ text: "username" }, c.get("language"))}
                name="username"
                minlength={3}
                maxlength={20}
                required
              />
            </label>
            <Help
              text={Locale({ text: "idHelp" }, c.get("language"))}
              lang={c.get("language")}
            />
          </div>
          
          <div>
            <label class={`
              input
              w-70
              m-3
            `}>
              <span class="label">
                <Icon
                  icon="material-symbols:mail"
                  color="#A4A7A9"
                />
              </span>
              <input
                type="email"
                placeholder="info@mail.example.com"
                name="email"
                required
              />
            </label>
            <Help
              text={Locale({ text: "mailHelp" }, c.get("language"))}
              lang={c.get("language")}
            />
          </div>
          
          <div>
            <label class={`
              input
              w-70
              m-3
            `}>
              <span class="label">
                <Icon
                  icon="material-symbols:key-rounded"
                  color="#A4A7A9"
                />
              </span>
              <input
                type="password"
                placeholder={Locale({ text: "password" }, c.get("language"))}
                name="password"
                minlength={8}
                maxlength={15}
                required
              />
            </label>
            <Help
              text={Locale({ text: "passwordHelp" }, c.get("language"))}
              lang={c.get("language")}
            />
          </div>
          
          <label class="label mb-3">
            <input
              type="checkbox"
              class="checkbox"
              name="agreeRule"
              required
            />
            {toComponent(Locale({ text: "agreeRule" }, c.get("language")))}
          </label>
          
          {TurnstileEnabled && (
            <Turnstile
              sitekey={TurnstileKeys[0]}
              button={html`[name='submit']`}
            />
          )}
          
          <button
            class={`
              btn
              btn-primary
              m-3
            `}
            type="submit"
            name="submit"
            disabled
          >
            <Icon icon="material-symbols:person-add-rounded" />
            {Locale({ text: "Signup" }, c.get("language"))}
          </button>
        </form>
      </main>
      
      <script src="/js/signup.js" />
    </Layout>
  );
});

export default SignUp;
