import axios, { AxiosError } from "axios";
import NextAuth, { NextAuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { JWT } from "next-auth/jwt";
import { Session } from "next-auth";

export const authOptions: NextAuthOptions = {
  providers: [
    CredentialsProvider({
      name: "credentials",
      credentials: {
        email: { label: "email", type: "text", },
        password: { label: "password", type: "password" }
      },
      async authorize(credentials) {
        const { email, password } = credentials as {
          email: string;
          password: string;
        };

        // console.log(email)
        // console.log(password)
        // console.log("NEXT_PUBLIC_API_BASE_URL")
        // console.log(process.env.NEXT_PUBLIC_API_BASE_URL)

        try {
          console.log(`${process.env.NEXT_PUBLIC_API_BASE_URL}admin/login`)
          const res = await axios.post(
            `${process.env.NEXT_PUBLIC_API_BASE_URL}admin/login`,
            { email, password }
          );
          console.log("res", res)

          // console.log(res)
          const user = res.data;
          console.log(user)
          if (res.status === 200 && user?.status) {
            return user.data;
          } else {
            throw new Error(user?.message || "Invalid credentials.");
          }
        } catch (error) {
          if (error instanceof AxiosError) {
            throw new Error(
              error.response?.data?.message || "Something went wrong"
            );
          }
          throw new Error("An unknown error occurred.");
        }
      },
    }),
  ],
  pages: {
    signIn: "/auth/signin",
    signOut: "/auth/signin",
  },
  callbacks: {
    // JWT callback
    // Use @ts-expect-error to indicate you expect a type error for the following line
    // @ts-expect-error: User and Admin types are incompatible but handled correctly in runtime
    jwt: async ({
      token,
      user,
      trigger,
      session,
    }: {
      token: JWT;
      user?: Admin; // Assuming Admin is defined elsewhere in your code
      trigger?: "signIn" | "signUp" | "update";
      session?: Session;
    }) => {
      if (user) {
        token.user = user;
        token.expires = Math.floor(Date.now() / 1000) + 24 * 60 * 60; // Set to 24 hours
      }
      if (trigger === "update" && session) {
        token.user = { ...session.user }; // Ensure you are updating user properties correctly
      }
      return token;
    },
    // Session callback
    session: async ({ session, token }: { session: Session; token: JWT }) => {
      session.user = token.user as typeof session.user;

      // Ensure token.expires is defined and of type number
      const expires = token.expires ? Number(token.expires) : undefined;

      if (expires) {
        // Check if the session has expired
        if (Date.now() >= expires * 1000) {
          session.expires = new Date(0).toISOString(); // Set expired session
        } else {
          session.expires = new Date(expires * 1000).toISOString(); // Set the valid expiration time
        }
      }
      return session;
    },
  },
  // JWT options for maxAge
  jwt: {
    maxAge: 24 * 60 * 60, // JWT expiration in 24h
  },
  session: {
    maxAge: 24 * 60 * 60, // Session expiration in 24h
    updateAge: 10, // Check every 10 seconds for an expired session
  },
};

export default NextAuth(authOptions);
