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

// 1. Definiamo i componenti stilizzati all'esterno (Zero stili inline)
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 SwitchText = styled("p")`
  margin: 16px 0 0;
  text-align: center;
  font-size: 14px;
  a {
    color: #007bff;
  }
`;

export default function Login() {
  const [email, setEmail] = createSignal("");
  const [password, setPassword] = createSignal("");
  const [loading, setLoading] = createSignal(false);
  // const [accessToken, setAccessToken] = createSignal(null);
  const navigate = useNavigate();

  const loginUser = (payload) => async () => {
    // const xsrfToken = getXsrfTokenFromCookie();
    const res = await fetch(`/api/login`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
      credentials: "include",
      body: JSON.stringify(payload),
    });
    return res;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);

    console.log("Inizio caricamento sessione...", {
      email: email(),
      password: password(),
    });

    try {
      // Simulazione attesa dati di sessione
      // await new Promise((resolve) => setTimeout(resolve, 1500));
      const login = loginUser({
        email: email(),
        password: password(),
      });
      const res = await login();
      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 a problem while logging in`);
        setLoading(false);
      }
    } catch (error) {
      console.error(error);
      setLoading(false);
    }
  };

  onMount(async () => {
    await prendiCookieIniziale();
  });

  return (
    <LoginLayout>
      <Container>
        <h2>Accedi al Portale</h2>
        <form onSubmit={handleSubmit}>
          <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
              disabled={loading()}
              autocomplete="username"
            />
          </FormGroup>
          <FormGroup style={{ "margin-bottom": "20px" }}>
            {" "}
            {/* Se preferisci puoi estrarre anche questo in un componente dedicato */}
            <Label htmlFor="password">Password</Label>
            <Input
              type="password"
              id="password"
              placeholder="Inserisci la tua password"
              value={password()}
              onInput={(e) => setPassword(e.currentTarget.value)}
              required
              disabled={loading()}
              autocomplete="current-password"
            />
          </FormGroup>
          <Button type="submit" disabled={loading()}>
            {loading() ? "Caricamento sessione..." : "Accedi"}
          </Button>
        </form>
        <SwitchText>
          not yet registered? <A href="/register">register here</A>
        </SwitchText>
      </Container>
    </LoginLayout>
  );
}
