"use client";

import "./auth.css";

import { FormEvent, useState } from "react";

import Image from "next/image";

const Homepage = () => {
  const [showSignup, setShowSignup] = useState(false);
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");

  const handleLoginSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    try {
      const response = await fetch(
        "https://milimanibackend.sigraelfasolutions.com/api/auth/login",
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          credentials: "include",
          body: JSON.stringify({ email, password }),
        }
      );

      const data = await response.json().catch(() => {
        console.error("Login: Failed to parse JSON");
        return { message: "Invalid server response" };
      });

      if (response.ok) {
        window.location.href = "/dashboard/admin";
      } else {
        alert(data.message || "Invalid login credentials");
      }
    } catch (err) {
      console.error("Login fetch failed:", err);
      alert("Network error. Please try again later.");
    }
  };

  const handleSignupSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    try {
      const response = await fetch(
        "https://milimanibackend.sigraelfasolutions.com/api/auth/signup",
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          credentials: "include",
          body: JSON.stringify({
            first_name: firstName,
            last_name: lastName,
            email,
            password,
          }),
        }
      );

      const data = await response.json().catch(() => {
        console.error("Signup: Failed to parse JSON");
        return { message: "Invalid server response" };
      });

      if (response.ok) {
        window.location.href = "/";
      } else {
        alert(data.message || "Signup failed");
      }
    } catch (err) {
      console.error("Signup fetch failed:", err);
      alert("Network error. Please try again later.");
    }
  };

  return (
    <div className="login-container">
      {/* LEFT SECTION */}
      <div className="login-left">
        <div className="logo">
          <Image src="/AIC_logo.png" alt="Logo" />
        </div>
        <Image
          src="/login_Image.jpg"
          alt="Login Visual"
          className="login-image"
        />
      </div>

      {/* RIGHT SECTION */}
      <div className="login-right">
        <div className={`form-popup ${showSignup ? "show-signup" : ""}`}>
          {/* LOGIN FORM */}
          <div className={`form-box login ${!showSignup ? "active" : ""}`}>
            <div className="form-details">
              <h2>Welcome Back</h2>
              <p>
                Please log in using your personal information to stay connected
                with us.
              </p>
            </div>
            <div className="form-content">
              <h2>LOGIN</h2>
              <form onSubmit={handleLoginSubmit}>
                <div className="input-field">
                  <input
                    type="text"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    required
                  />
                  <label>Email</label>
                </div>
                <div className="input-field">
                  <input
                    type="password"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    required
                  />
                  <label>Password</label>
                </div>
                <a href="#" className="forgot-pass-link">
                  Forgot password?
                </a>
                <button type="submit">Log In</button>
              </form>
              <div className="bottom-link">
                Don’t have an account?{" "}
                <a
                  href="#"
                  onClick={(e) => {
                    e.preventDefault();
                    setShowSignup(true);
                  }}
                >
                  Signup
                </a>
              </div>
            </div>
          </div>

          {/* SIGNUP FORM */}
          <div className={`form-box signup ${showSignup ? "active" : ""}`}>
            <div className="form-details">
              <h2>Create Account</h2>
              <p>
                To become a part of our community, please sign up using your
                personal information.
              </p>
            </div>
            <div className="form-content">
              <h2>SIGNUP</h2>
              <form onSubmit={handleSignupSubmit}>
                <div className="input-field">
                  <input
                    type="text"
                    value={firstName}
                    onChange={(e) => setFirstName(e.target.value)}
                    required
                  />
                  <label>First Name</label>
                </div>
                <div className="input-field">
                  <input
                    type="text"
                    value={lastName}
                    onChange={(e) => setLastName(e.target.value)}
                    required
                  />
                  <label>Last Name</label>
                </div>
                <div className="input-field">
                  <input
                    type="text"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    required
                  />
                  <label>Email</label>
                </div>
                <div className="input-field">
                  <input
                    type="password"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    required
                  />
                  <label>Password</label>
                </div>
                <div className="policy-text">
                  <input type="checkbox" id="policy" />
                  <label htmlFor="policy">
                    I agree to the{" "}
                    <a href="#" className="option">
                      Terms & Conditions
                    </a>
                  </label>
                </div>
                <button type="submit">Sign Up</button>
              </form>
              <div className="bottom-link">
                Already have an account?{" "}
                <a
                  href="#"
                  onClick={(e) => {
                    e.preventDefault();
                    setShowSignup(false);
                  }}
                >
                  Login
                </a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Homepage;
