"use client";
import { createContext, ReactNode, useContext, useEffect } from "react";
import {
  useQuery,
  useMutation,
  UseMutationResult,
} from "@tanstack/react-query";
import { getQueryFn, apiRequest, queryClient } from "../lib/queryClient";
import { useToast } from "@/hooks/use-toast";
import { User } from "@/models/User";
import { API_URL } from "@/lib/constants";

type AuthContextType = {
  user: User | null;
  isLoading: boolean;
  isAuthenticated: boolean;
  error: Error | null;
  loginMutation: UseMutationResult<User, Error, LoginData>;
  logoutMutation: UseMutationResult<any, any, void, unknown>;
  registerMutation: UseMutationResult<User, Error, RegisterData>;
};

type LoginData = {
  username: string;
  password: string;
};

type RegisterData = {
  fullName: string;
  username: string;
  password: string;
  email: string;
};

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

export function AuthProvider({ children }: { children: ReactNode }) {
  const { toast } = useToast();
  const {
    data: user,
    error,
    isLoading,
    refetch: refetchUser,
  } = useQuery<any>({
    queryKey: ["/current_user"],
    queryFn: async ({ queryKey }) => {
      try {
        const res = await fetch(`${API_URL}${queryKey[0]}`, {
          credentials: "include",
        });

        if (res.status === 401) {
          return null;
        }

        if (!res.ok) {
          throw new Error(`Failed to fetch user session: ${res.statusText}`);
        }

        return res.json();
      } catch (error: any) {
        console.error("Session fetch error:", error);
        return null;
      }
    },
    retry: false,
    refetchOnWindowFocus: false,
    staleTime: 1000 * 60 * 5, // 5 minutes
  });

  const loginMutation = useMutation({
    mutationFn: async (credentials: LoginData) => {
      const res: any = await apiRequest("POST", "/login", credentials);
      return res;
    },
    onSuccess: (user: User) => {
      queryClient.setQueryData(["/user"], user);
      toast({
        title: "Login successful",
        description: `Welcome back, ${user.fullName}!`,
      });
      setTimeout(() => {
        // redirect to home
        window.location.href = "/";
      }, 500);
    },
    onError: (error: Error) => {
      toast({
        title: "Login failed",
        description: error.message || "Invalid username or password",
        variant: "destructive",
      });
    },
  });

  const registerMutation = useMutation({
    mutationFn: async (credentials: RegisterData): Promise<any> => {
      const res = await apiRequest("POST", "/register", credentials);
      return res;
    },
    onSuccess: (user: User) => {
      queryClient.setQueryData(["/user"], user);
      toast({
        title: "Registration successful",
        description: "Your account has been created!",
      });
    },
    onError: (error: Error) => {
      toast({
        title: "Registration failed",
        description:
          error.message ||
          "Failed to create account. Please try different credentials.",
        variant: "destructive",
      });
    },
  });

  const logoutMutation = useMutation({
    mutationFn: async () => {
      const res = await apiRequest("POST", "/logout");
      return res;
    },
    onSuccess: () => {
      queryClient.setQueryData(["/user"], null);
      // Redirect to home page
      window.location.href = "/";
      toast({
        title: "Logged out successfully",
      });
    },
    onError: (error: Error) => {
      toast({
        title: "Logout failed",
        description: error.message,
        variant: "destructive",
      });
    },
  });

  // Update auth state when the token is about to expire
  useEffect(() => {
    if (user?.expiresAt) {
      const expiresAt = new Date(user.expiresAt).getTime();
      const now = Date.now();
      const timeToExpire = expiresAt - now;

      // Refresh token 5 minutes before expiration
      if (timeToExpire > 0 && timeToExpire < 1000 * 60 * 5) {
        const refreshTimer = setTimeout(() => {
          refetchUser();
        }, timeToExpire - 1000 * 60 * 5);

        return () => clearTimeout(refreshTimer);
      }
    }
  }, [user, refetchUser]);
  return (
    <AuthContext.Provider
      value={{
        user: user ?? null,
        isAuthenticated: !!user,
        isLoading,
        error,
        loginMutation,
        logoutMutation,
        registerMutation,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
}

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