// app/login/page.tsx

"use client";

import React, { useState, useEffect, Suspense } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import LoginModal from "../features/Auth/LoginModal";
import Modal from "../components/Modal/Modal";
import "./page.scss";

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

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  useEffect(() => {
    const checkAuthStatus = async () => {
      // Optionally implement
    };
    checkAuthStatus();
  }, []);

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

      if (response.ok) {
        setIsLoggedIn(true);
        router.replace(redirectPath);
        return true;
      } else {
        setIsLoggedIn(false);
        return false;
      }
    } catch (error) {
      console.error("Login failed:", error);
      setIsLoggedIn(false);
      return false;
    }
  };

  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>

      <Modal
        open={true}
        onClose={() => {}}
        title="Login to Backoffice"
      >
        <LoginModal onLogin={handleLogin} />
      </Modal>
    </div>
  );
}

// ✅ Export wrapped in Suspense
export default function LoginPage() {
  return (
    <Suspense fallback={null}>
      <LoginPageContent />
    </Suspense>
  );
}
