"use client";
import React, { FormEvent, useEffect, useState } from "react";
import {
  Card,
  Typography,
  Input,
  Checkbox,
  Button,
} from "@material-tailwind/react";
import Image from "next/image";
import Link from "next/link";
import { Account } from "@/api/account.api";
import { redirect, useRouter } from "next/navigation";
import { Loading } from "@/ui/loader/loading";

export default function Login() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [erreur, setError] = useState("");
  const router = useRouter();
  const handleLogin = async (e: FormEvent) => {
    e.preventDefault();
    setIsLoading(true);

    try {
      setError("");
      const response = await Account.login({
        username: email,
        password: password,
      });

      console.log("Authentification réussie", response);
      setIsLoading(false);
      Account.saveToken(response.token);
      router.push("/formation");
    } catch (error) {
      setIsLoading(false);
      setError("Login ou mot de passe incorrect!");
      setPassword("");
      console.error("Erreur d'authentification", error);
    }
  };
  useEffect(() => {
    if (Account.isAuth()) {
      router.push("/");
    }
  }, []);

  return (
    <div className="h-screen flex justify-center items-center">
      {isLoading && <Loading />}
      <Card
        color="transparent"
        className="flex flex-col justify-center"
        shadow={false}
      >
        <Image
          src="/assets/img-bsl/logo bsl.png"
          alt="logo"
          className="m-auto"
          width="200"
          height="48"
        />
        <Typography variant="h4" className="text-center" color="blue-gray">
          Connexion
        </Typography>
        <Typography color="gray" className="mt-1 text-center font-normal">
          Remplissez les champs suivants pour vous connecter
        </Typography>

        <Typography color="red" className="text-center">
          {erreur}
        </Typography>
        <form
          onSubmit={handleLogin}
          className="mt-5 mx-auto mb-2 w-80 max-w-screen-lg sm:w-96"
        >
          <div className="mb-4 flex flex-col gap-6">
            <Input
              required
              size="lg"
              label="Email"
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              crossOrigin={undefined}
            />
            <Input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              size="lg"
              label="Mot de passe"
              crossOrigin={undefined}
              required
            />
          </div>

          <Button type="submit" className="mt-6 bg-vert_fonce" fullWidth>
            Connexion
          </Button>
        </form>
        <Typography color="gray" className="mt-4 text-center font-normal">
          Pas encore de compte?{" "}
          <Link href="/account/register" className="font-medium text-gray-900">
            S'enregistrer
          </Link>
        </Typography>
      </Card>
    </div>
  );
}
