import { createSignal } from "solid-js";
import { A, useNavigate } from "@solidjs/router";
import { styled } from "solid-styled-components";
import LoginLayout from "~/components/LoginLayout";
import { accessToken, setAccessToken } from "~/hooks/accessToken";
import { setLStoken } from "~/utils/getLStoken";
import { setIsLoggedIn } from "~/hooks/isLogged";
import { setUser } from "~/hooks/user";
import { baseUrl } from "~/utils/urls";

const Container = styled("div")`
  max-width: 400px;
  margin: 50px auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 8px;
`;

const FormGroup = styled("div")`
  margin-bottom: 15px;
`;

const Label = styled("label")`
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
`;

const Input = styled("input")`
  width: 100%;
  padding: 8px;
  box-sizing: border-box;
`;

const Button = styled("button")`
  width: 100%;
  padding: 10px;
  background-color: ${(props) => (props.disabled ? "#cccccc" : "#007bff")};
  color: white;
  border: none;
  border-radius: 4px;
  cursor: ${(props) => (props.disabled ? "not-allowed" : "pointer")};
  font-size: 16px;
`;

const ErrorText = styled("p")`
  margin: 0 0 12px;
  color: #b00020;
  font-size: 14px;
  min-height: 1.2em;
`;

const SwitchText = styled("p")`
  margin: 16px 0 0;
  text-align: center;
  font-size: 14px;
  a {
    color: #007bff;
  }
`;

export default function Register() {
  const [name, setName] = createSignal("");
  const [email, setEmail] = createSignal("");
  const [password, setPassword] = createSignal("");
  const [confirmPassword, setConfirmPassword] = createSignal("");
  const navigate = useNavigate();
  let errorEl;

  const handleSubmit = async (e) => {
    e.preventDefault();
    const passwordValue = e.currentTarget.querySelector("#password").value;
    const confirmValue =
      e.currentTarget.querySelector("#confirm-password").value;
    errorEl.textContent =
      passwordValue !== confirmValue ? "Le password non coincidono" : "";

    const res = await fetch(`/api/register`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json", // Costringe Laravel a rispondere in formato JSON
        // "X-XSRF-TOKEN": xsrfToken,
        Authorization: `Bearer ${accessToken()}`,
      },
      credentials: "include", // <--- Dice al browser di memorizzare i cookie ricevuti
      body: JSON.stringify({
        name: name(),
        email: email(),
        password: password(),
        password_confirmation: confirmPassword(),
      }),
    });
    if (res.ok) {
      try {
        const { access_token, message, status, token_type, user } =
          await res.json();
        console.log(access_token);
        setAccessToken(access_token);
        setLStoken(accessToken());
        setIsLoggedIn(true);
        setUser(user);
        console.log("Sessione caricata!");
        // Inoltra l'utente eliminando il login dalla cronologia
        navigate("/", { replace: true });
      } catch (error) {
        console.log(
          `Errore durante il processo di lettura del JSON di risposta: `,
          error,
        );
      }
    } else {
      console.log(`There was an error in the registration process: `, res);
    }
  };

  return (
    <LoginLayout>
      <Container>
        <h2>Registrati</h2>
        <form onSubmit={handleSubmit}>
          <FormGroup>
            <Label htmlFor="name">Name</Label>
            <Input
              type="text"
              id="name"
              placeholder="Il tuo nome"
              value={name()}
              onInput={(e) => setName(e.currentTarget.value)}
              required
              autocomplete="name"
            />
          </FormGroup>
          <FormGroup>
            <Label htmlFor="email">Indirizzo Email</Label>
            <Input
              type="email"
              id="email"
              placeholder="esempio@email.com"
              value={email()}
              onInput={(e) => setEmail(e.currentTarget.value)}
              required
              autocomplete="email"
            />
          </FormGroup>
          <FormGroup>
            <Label htmlFor="password">Password</Label>
            <Input
              type="password"
              id="password"
              placeholder="Inserisci la tua password"
              value={password()}
              onInput={(e) => setPassword(e.currentTarget.value)}
              required
              autocomplete="new-password"
            />
          </FormGroup>
          <FormGroup style={{ "margin-bottom": "20px" }}>
            <Label htmlFor="confirm-password">Conferma Password</Label>
            <Input
              type="password"
              id="confirm-password"
              placeholder="Ripeti la password"
              value={confirmPassword()}
              onInput={(e) => setConfirmPassword(e.currentTarget.value)}
              required
              autocomplete="new-password"
            />
          </FormGroup>
          <ErrorText ref={errorEl} />
          <Button type="submit">Registrati</Button>
        </form>
        <SwitchText>
          already registered? <A href="/login">login</A>
        </SwitchText>
      </Container>
    </LoginLayout>
  );
}
