"use client";
import { useState } from "react";
import { loginUser } from "@/app/lib/login";
import { useRouter } from "next/navigation";

import Swal from "sweetalert2";
import "./Login.css";

export default function Login() {
  const [user, setUser] = useState("");
  const [password, setPassword] = useState("");

  const router = useRouter();

  const handleLogin = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    if (!user) {

      Swal.fire({
        title: "Coloca un usuario!",
        icon: "error",
        draggable: true,
      });
      return;
    }

    if (!password) {

      Swal.fire({
        title: "Coloca una contraseña!",
        icon: "error",
        draggable: true,
      });
      return;
    }

    const data = await loginUser(user, password);

    if ("error" in data) {
      Swal.fire({
        title: data.error,
        icon: "error",
        draggable: true,
      });
    } else {
      const token = data.access_token;
      const payload = JSON.parse(atob(token.split(".")[1]));
      const usuario = payload.usuario;
      const role = payload.role;

      document.cookie = `token=${token}; path=/; SameSite=Strict`;
      document.cookie = `user=${usuario}; path=/; SameSite=Strict`;
      document.cookie = `role=${role}; path=/; SameSite=Strict`;


      Swal.fire({
        title: "Inicio de sesión exitoso!",
        icon: "success",
        draggable: true,
      });
      router.push("/Impresiones");
      router.refresh();
    }
  };

  return (
    <section className="centerGrid containerSection">
      <form className="login" onSubmit={handleLogin}>
        <h2 className="title">Bienvenido a AT</h2>

        <div className="containerInput">
          <label className="label">Usuario</label>
          <input
            type="text"
            value={user}
            onChange={(e) => setUser(e.target.value)}
            placeholder="Coloca tu usuario..."
          />
        </div>

        <div className="containerInput relative">
          <label className="label">Contraseña</label>
          <input
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            placeholder="Coloca tu contraseña..."
          />
          <span
          //onClick={() => setShowPassword(!showPassword)}
          //className={showPassword ? 'eyeOpen' : 'eyeClose'}
          />
        </div>

        <button
          className="button buttonSearch"
          style={{ maxWidth: "100%", width: "100%" }}
          type="submit"
        >
          Iniciar sesión
        </button>
      </form>
    </section>
  );
}
//IO
