import { NextAuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import GoogleProvider from "next-auth/providers/google";
import FacebookProvider from "next-auth/providers/facebook";
// import { PrismaAdapter } from '@auth/prisma-adapter';
import { prisma } from "@/lib/prisma";
import bcrypt from "bcryptjs";
import { UserRole } from "@prisma/client";
import { cookies } from "next/headers";
// import { getCountryDataByDomain } from '@/lib/countries';

// const datacounter =    getCountryDataByDomain();

export const authOptions: NextAuthOptions = {
  // adapter: PrismaAdapter(prisma),
  session: {
    strategy: "jwt",
    maxAge: 30 * 24 * 60 * 60, // 30 days max (will be overridden by JWT exp)
  },
  jwt: {
    maxAge: 30 * 24 * 60 * 60, // 30 days max
  },
  cookies: {
    sessionToken: {
      name: `next-auth.session-token`,
      options: {
        httpOnly: true,
        sameSite: "lax",
        path: "/",
        secure: false, // Set to false for HTTP deployment
        maxAge: 30 * 24 * 60 * 60, // 30 days max
      },
    },
  },
  pages: {
    signIn: "/login",
    signOut: "/",
    error: "/auth/error",
  },
  providers: [
    CredentialsProvider({
      name: "credentials",
      credentials: {
        email: { label: "Email", type: "email" },
        password: { label: "Password", type: "password" },
        remember: { label: "Remember Me", type: "text" },
      },
      async authorize(credentials) {
        if (!credentials?.email || !credentials?.password) {
          throw new Error("Invalid credentials");
        }

        const user = await prisma.user.findUnique({
          where: {
            email: credentials.email,
          },
          include: {
            profile: true,
          },
        });

        if (!user || !user.password) {
          throw new Error("Invalid credentials");
        }

        const isPasswordValid = await bcrypt.compare(
          credentials.password,
          user.password
        );

        if (!isPasswordValid) {
          throw new Error("Invalid credentials");
        }

        // Construct full name from profile
        const fullName = user.profile
          ? `${user.profile.firstName || ""} ${
              user.profile.lastName || ""
            }`.trim()
          : user.email?.split("@")[0] || "User";

        return {
          id: user.id,
          email: user.email,
          name: fullName,
          role: user.role,
          image: user.profile?.profileImage || user.image,
          remember: credentials.remember === "true",
        };
      },
    }),
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
      authorization: {
        url: "https://accounts.google.com/o/oauth2/v2/auth",
        params: {
          prompt: "select_account",
          access_type: "offline",
        },
      },
    }),
    FacebookProvider({
      clientId: process.env.FACEBOOK_CLIENT_ID!,
      clientSecret: process.env.FACEBOOK_CLIENT_SECRET!,
      authorization: {
        params: {
          scope: "email public_profile",
        },
      },
    }),
  ],
  callbacks: {
    async jwt({ token, user, account }) {
      if (user) {
        // urser role is here
        if (!user.role) {
          const dbUser = await prisma.user.findUnique({
            where: { email: user.email! },
            select: { id: true, role: true },
          });
          token.role = dbUser?.role || token.role || UserRole.FREELANCER;
        } else {
          token.role = user.role;
        }
        // urser role is here

        token.id = user.id;
        token.name = user.name;
        // token.role = user.role;
        token.remember = user.remember;

        // Set initial expiration time based on remember me preference
        const now = Math.floor(Date.now() / 1000);
        if (user.remember) {
          // Remember me: 30 days
          token.exp = now + 30 * 24 * 60 * 60;
        } else {
          // Normal: 24 hours
          token.exp = now + 24 * 60 * 60;
        }
      }

      if (account) {
        token.provider = account.provider;
      }

      // If this is not the initial sign-in, check if we need to refresh
      if (
        !user &&
        token.remember &&
        token.exp &&
        typeof token.exp === "number"
      ) {
        const now = Math.floor(Date.now() / 1000);
        // If token is close to expiring (within 1 hour) and remember me is enabled, refresh it
        if (token.exp - now < 3600) {
          token.exp = now + 30 * 24 * 60 * 60; // Extend for another 30 days
        }
      }

      return token;
    },
    async session({ session, token }) {
      if (session.user) {
        session.user.id = token.id;
        session.user.name = token.name as string;
        session.user.role = token.role;
        session.user.provider = token.provider;
        session.user.remember = token.remember;
      }
      return session;
    },
    async signIn({ user, account }) {
      const cookieStore = cookies();
      const countryId = (await cookieStore).get("country")?.value;

      

      if (account?.provider === "google" || account?.provider === "facebook") {
        try {
          const existingUser = await prisma.user.findUnique({
            where: { email: user.email! },
          });

          if (!existingUser) {
            // Create new user with OAuth provider
            const newUser = await prisma.user.create({
              data: {
                email: user.email!,
                image: user.image,
                provider: account.provider,
                providerId: account.providerAccountId,
                role: UserRole.FREELANCER, // Default role for new users
                emailVerified: new Date(),
              },
            });

            // Create a basic profile for the new user
            if (user.name) {
              const nameParts = user.name.split(" ");
              const firstName = nameParts[0] || "";
              const lastName = nameParts.slice(1).join(" ") || "";

              await prisma.profile.create({
                data: {
                  userId: newUser.id,
                  firstName,
                  lastName,
                  profileImage: user.image,
                  countryId: countryId || "switzerland", // Default to Switzerland
                },
              });
            }
          }
        } catch (error) {
          console.error("Error in signIn callback:", error);
          return false;
        }
      }
      return true;
    },
  },
};
