'use client'
import Image from "next/image";
import React, {useEffect, useState} from "react";
import { useRouter } from 'next/navigation';
import Cookies from "js-cookie";
import "./login.css";
import {getToken} from "../services/global";

export default function Login() {

  useEffect(() => {
    const token = getToken();

    if (token) {
      router.push('/')
    }
  }, []);


  const router = useRouter();
  const [formData, setFormData] = useState({
    email: "",
    password: "",
  });
  const [loginStatus, setLoginStatus] = useState("");

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value,
    });
  };

  const handleSubmit = async (e: React.MouseEvent<HTMLButtonElement>) => {
    e.preventDefault();

    // Send a POST request to your login API route
    const response = await fetch("http://service.demowebsitelinks.com:5000/api/auth/login", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(formData),
    });

    if (response.ok) {
      // Parse the JSON response
      const data = await response.json();
      console.log(data);
      // Save the token in a cookie
      Cookies.set("user_id", data.data._id);
      Cookies.set("token", data.token);

      // Redirect to the dashboard or desired page
      router.push("/");
    } else {
      // Handle login errors, show a message, etc.
      setLoginStatus("error");
      console.error("Login failed");
    }
  };

  return (
      <>
        <div className="loginPg">
          <header className="">
            <Image src="/vercel.svg" alt="Vercel Logo" width={100} height={24} priority />
          </header>
          <div className="imgOverlay">
            <Image
                className="w-full h-screen object-cover absolute inset-0"
                src="/images/loginBg.png" // Path is relative to the public directory
                alt="Description of the image"
                width={1920}
                height={1200}
            />
            <h1 className="textWrapper">Enter your logo name</h1>
          </div>
          <div className="loginBox">
            <div className="headingBox">
              <h2>Sign in to logo maker</h2>
              <p>You can always make changes later</p>
            </div>
            <div className="flex flex-col w-[450px]">
              <div className="inputCont">
                <label htmlFor="email">Email</label>
                <input
                    type="email"
                    id="email"
                    name="email"
                    value={formData.email}
                    onChange={handleChange}
                    autoFocus
                    required
                />
              </div>
              <div className="inputCont">
                <label htmlFor="password">
                  Password
                  {/*<a href="">Forget?</a>*/}
                </label>
                <input
                    type="password"
                    id="password"
                    name="password"
                    value={formData.password}
                    onChange={handleChange}
                    required
                />
              </div>
              {loginStatus === "error" && (
                  <p className="validationError">Invalid email or password. Please try again.</p>
              )}
              <button type="button" className="themeBtn" onClick={handleSubmit}>
                Sign in
              </button>
              <p className="signupText">
                Don’t have an account? <a href="/signup">Sign up</a>
              </p>
            </div>
          </div>
        </div>
      </>
  );
}
