import { createContext, useContext, useState, useEffect, ReactNode } from "react";
import { useMutation } from "@tanstack/react-query";
import { queryClient } from "@/client/rpc-client";

interface User {
  id: string;
  username: string;
  email: string;
  role: "customer" | "owner";
}

interface AuthContextType {
  user: User | null;
  sessionId: string | null;
  isLoading: boolean;
  login: (username: string, password: string) => Promise<void>;
  logout: () => void;
  isOwner: boolean;
}

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

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

interface AuthProviderProps {
  children: ReactNode;
}

export function AuthProvider({ children }: AuthProviderProps) {
  const [user, setUser] = useState<User | null>(null);
  const [sessionId, setSessionId] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  const { mutateAsync: loginMutation } = useMutation(
    queryClient.auth.login.mutationOptions()
  );

  const { mutateAsync: logoutMutation } = useMutation(
    queryClient.auth.logout.mutationOptions()
  );

  const { mutateAsync: verifySessionMutation } = useMutation(
    queryClient.auth.verifySession.mutationOptions()
  );

  useEffect(() => {
    // Check for existing session on app load
    const storedSessionId = localStorage.getItem("sessionId");
    if (storedSessionId) {
      verifySessionMutation(storedSessionId)
        .then((result) => {
          setUser(result.user);
          setSessionId(storedSessionId);
        })
        .catch(() => {
          localStorage.removeItem("sessionId");
        })
        .finally(() => {
          setIsLoading(false);
        });
    } else {
      setIsLoading(false);
    }
  }, [verifySessionMutation]);

  const login = async (username: string, password: string) => {
    try {
      const result = await loginMutation({ username, password });
      setUser(result.user);
      setSessionId(result.sessionId);
      localStorage.setItem("sessionId", result.sessionId);
    } catch (error) {
      throw error;
    }
  };

  const logout = async () => {
    if (sessionId) {
      try {
        await logoutMutation(sessionId);
      } catch (error) {
        // Continue with logout even if server call fails
        console.error("Logout error:", error);
      }
    }
    
    setUser(null);
    setSessionId(null);
    localStorage.removeItem("sessionId");
  };

  const isOwner = user?.role === "owner";

  const value: AuthContextType = {
    user,
    sessionId,
    isLoading,
    login,
    logout,
    isOwner,
  };

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  );
}