"use client";

import { createContext, useContext, useEffect, useState } from "react";
import { useAuthenticateUser, useRegisterUser } from "@/api/mangamochi";
import { useRouter } from "next/navigation";
import { toast } from "sonner";

export interface UserPreferences {
  theme: "light" | "dark";
  itemsPerPage: number;
  defaultGenres: string[];
}

export interface User {
  id: number;
  email: string;
  name: string;
  token: string;
  role: string;
  // preferences: UserPreferences
}

interface AuthContextType {
  user: User | null;
  isLoading: boolean;
  isAuthenticated: boolean;
  register: (
    email: string,
    password: string,
    username: string,
  ) => Promise<void>;
  login: (email: string, password: string) => Promise<void>;
  logout: () => void;
  // updatePreferences: (preferences: Partial<UserPreferences>) => void
}

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

export function AuthProvider({ children }: { children: React.ReactNode }) {
  const router = useRouter();

  const [user, setUser] = useState<User | null>(null);

  const { mutate: mutateRegisterUser, isPending: isPendingRegisterUser } =
    useRegisterUser({
      mutation: {
        onSuccess: () => {
          router.push("/login");
          toast.success("Registration successful! You can now login.");
        },
      },
    });

  const { mutate: mutateAuthenticateUser, isPending: isPendingLoginUser } =
    useAuthenticateUser({
      mutation: {
        onSuccess: (response) => {
          if (!response.data) {
            return;
          }

          const userData: User = {
            id: response.data.id,
            email: response.data.email,
            name: response.data.name,
            token: response.data.token,
            role: response.data.role,
          };

          setUser(userData);

          localStorage.setItem("userData", JSON.stringify(userData));

          router.push("/");
        },
      },
    });

  const register = async (email: string, password: string, name: string) => {
    console.log(email);
    mutateRegisterUser({ data: { name, email, password } });
  };

  const login = async (email: string, password: string) => {
    mutateAuthenticateUser({ data: { email, password } });
  };

  const logout = () => {
    setUser(null);
    localStorage.removeItem("userData");
  };

  // const updatePreferences = (preferences: Partial<UserPreferences>) => {
  //     if (!user) return
  //
  //     const updatedUser = {
  //         ...user,
  //         preferences: {
  //             ...user.preferences,
  //             ...preferences,
  //         },
  //     }
  //     setUser(updatedUser)
  // }

  useEffect(() => {
    const jsonString = localStorage.getItem("userData");
    if (jsonString) {
      const userData: User = JSON.parse(jsonString);
      setUser(userData);
    }
  }, []);

  return (
    <AuthContext.Provider
      value={{
        user,
        isLoading: isPendingLoginUser || isPendingRegisterUser,
        isAuthenticated: !!user,
        register,
        login,
        logout,
        // updatePreferences,
      }}
    >
      {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;
}
