"use client";

import {
  ReactNode,
  createContext,
  useContext,
  useEffect,
  useState,
} from "react";

import type { User } from "./types";

interface AuthContextType {
  user: User | null;
  setUser: (user: User | null) => void;
  isInitialized: boolean;
  login: (
    username: string,
    password: string,
  ) => Promise<{ ok: boolean; status?: number }>;
  logout: () => void;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export function AuthProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<User | null>(null);
  const [isInitialized, setIsInitialized] = useState(false);

  useEffect(() => {
    const savedUser = localStorage.getItem("coffee-shop-user");
    if (savedUser) {
      try {
        setUser(JSON.parse(savedUser));
      } catch (e) {
        console.error("Failed to parse saved user", e);
      }
    }
    setIsInitialized(true);
  }, []);

  const login = async (
    username: string,
    password: string,
  ): Promise<{ ok: boolean; status?: number }> => {
    const isPhone = /^0\d{9}$/.test(username.trim());
    const role = isPhone ? "customer" : "manager";

    try {
      const response = await fetch("/api/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ phone: username, password, role }),
      });

      if (response.ok) {
        const userData = await response.json();
        setUser(userData);
        localStorage.setItem("coffee-shop-user", JSON.stringify(userData));
        return { ok: true };
      } else {
        console.error("Đăng nhập thất bại:", response.status);
        return { ok: false, status: response.status };
      }
    } catch (error) {
      console.error("Lỗi kết nối API:", error);
      return { ok: false };
    }
  };

  const logout = () => {
    setUser(null);
    localStorage.removeItem("coffee-shop-user");
  };

  return (
    <AuthContext.Provider
      value={{
        user,
        setUser,
        isInitialized,
        login,
        logout,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
}

export function useAuth() {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error("useAuth must be used within an AuthProvider");
  }
  return context;
}
