import { Login} from "../Components/Form/Login/Login.jsx"
import { SignUp } from "../Components/Form/SignUp/SignUp";
import { toast } from "react-toastify";
import { Auth } from "../Components/Auth/Auth.jsx";
import { getUserByPhone,postUser } from "../Api/userApi.js";
export const AuthPage = () => {
  const handleLogin = async (phoneNumber) => {
    try {
      const response = await fetch(`http://192.168.1.59:3000/users?phoneNumber=${phoneNumber}`);
      const users = await response.json();

      if (users.length > 0) {
        const user = users[0];
        localStorage.setItem("user", JSON.stringify(user));
        window.location.replace("/select-seat");
      } else {
        toast.warn("User not found. Please register or check the number.");
      }
    } catch (error) {
      console.error("Login error:", error);
      toast.error("Failed to login. Please try again.");
    }
  };

  const handleSignUp = async (formData) => {
    try {
      if (!formData || !formData.phoneNumber) {
        toast.error("Invalid form data");
        return;
      }

      const response = await getUserByPhone(formData.phoneNumber);
      if (response.data.length > 0) {
        toast.warn("Phone number already registered.");
        return;
      }

      const newUser = { ...formData, reservedSeats: [] };
      const postRes = await postUser(newUser);

      if (postRes.status === 201) {
        localStorage.setItem("user", JSON.stringify(postRes.data));
        toast.success("Account created successfully!");
      } else {
        toast.error("Failed to create account. Try again.");
      }
    } catch (error) {
      console.error("Sign up error:", error);
      toast.error("Network error or server not available.");
    }
  };

  return (
    <Auth
      LoginComponent={Login}
      SignUpComponent={SignUp}
      onLoginSubmit={handleLogin}
      onSignUpSubmit={handleSignUp}
    />
  );
};
