"use client";

import React, { useState, useEffect } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import LoginModal from "../features/Auth/LoginModal"; // Your LoginModal component

import "./page.scss"; // Global styles for LoginModal and page
import Modal from "../components/Modal/Modal";

export default function LoginPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const redirectPath = searchParams.get("redirect") || "/dashboard";

  const [authMessage, setAuthMessage] = useState("");
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  useEffect(() => {
    // Check if already logged in by trying to fetch a protected resource or checking a client-accessible flag
    // For HTTP-only cookies, you can't directly read the token here.
    // Instead, you'd rely on a server-side check (e.g., in middleware or a Server Component)
    // or a simple client-side flag if your backend also sets one (less secure for token itself).
    // For this example, we'll assume if they land here, they need to log in.
    // A more robust check might involve a quick API call to /api/auth/status
    // if the token is in an HTTP-only cookie.
    const checkAuthStatus = async () => {
      // In a real app, this might be a call to a /api/auth/status endpoint
      // that checks the HTTP-only cookie on the server and returns a boolean.
      // For now, we'll rely on the middleware to redirect if unauthenticated.
      // If the user somehow lands on /login with a valid cookie, the middleware
      // should have redirected them already.
    };
    checkAuthStatus();
  }, []);

  const handleLogin = async (email: string, password: string) => {
    setAuthMessage("Attempting login...");
    try {
      const response = await fetch("/api/auth/login", {
        // <--- CALLING YOUR INTERNAL ROUTE HANDLER
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ email, password }),
      });

      const data = await response.json();

      if (response.ok) {
        // Check if the response status is 2xx
        // Backend has successfully set the HTTP-only cookie
        setAuthMessage("Login successful!");
        setIsLoggedIn(true);
        // Redirect to the intended path after successful login
        router.replace(redirectPath);
      } else {
        // Handle login errors (e.g., invalid credentials)
        setAuthMessage(data.message || "Login failed. Please try again.");
        setIsLoggedIn(false);
      }
    } catch (error) {
      console.error("Login failed:", error);
      setAuthMessage("An error occurred during login. Please try again later.");
      setIsLoggedIn(false);
    }
    return isLoggedIn; // Return the current login status
  };

  const clearAuthMessage = () => setAuthMessage("");

  // If user is already logged in (e.g., redirected by middleware to dashboard),
  // this page shouldn't be visible. The middleware should handle the primary redirect.
  // This `isLoggedIn` state here is more for internal page logic if the user somehow
  // bypasses middleware or lands on /login with a valid session.
  // For a robust setup, the middleware is key.

  return (
    <div className="page-container">
      <div className="page-container__content">
        <h1 className="page-container__title">Payment Backoffice</h1>
        <p className="page-container__text">
          Please log in to access the backoffice.
        </p>
      </div>

      {/* Always show the modal on the login page */}
      <Modal
        open={true} // Always open on the login page
        onClose={() => {
          /* No direct close for login modal, user must log in */
        }}
        title="Login to Backoffice"
      >
        <LoginModal
          onLogin={handleLogin} // Pass the API call function
          authMessage={authMessage}
          clearAuthMessage={clearAuthMessage}
        />
      </Modal>
    </div>
  );
}
