import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import axios from 'axios';

const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';

interface AuthState {
  token: string | null;
  user: { userId: string; email: string } | null;
  credentials: { email: string; password: string } | null;
  googleCredential: string | null;
  isAuthenticated: boolean;
  login: (email: string, password: string) => Promise<void>;
  loginWithGoogle: (credential: string) => Promise<void>;
  logout: () => void;
  checkAuth: () => void;
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set, get) => ({
      token: null,
      user: null,
      credentials: null,
      googleCredential: null,
      isAuthenticated: false,

      login: async (email: string, password: string) => {
        try {
          const response = await axios.post(`${API_URL}/api/auth/login`, {
            email,
            password,
          });

          const { token } = response.data;

          // Verify token to get user info
          const verifyResponse = await axios.post(`${API_URL}/api/auth/verify`, {
            token,
          });

          if (verifyResponse.data.valid) {
            set({
              token,
              user: verifyResponse.data.user,
              credentials: { email, password },
              isAuthenticated: true,
            });
          }
        } catch (error) {
          console.error('Login failed:', error);
          throw error;
        }
      },

      loginWithGoogle: async (credential: string) => {
        try {
          const response = await axios.post(`${API_URL}/api/auth/google`, {
            credential,
          });

          const { token } = response.data;

          const verifyResponse = await axios.post(`${API_URL}/api/auth/verify`, {
            token,
          });

          if (verifyResponse.data.valid) {
            set({
              token,
              user: verifyResponse.data.user,
              credentials: null,
              googleCredential: credential,
              isAuthenticated: true,
            });
          }
        } catch (error) {
          console.error('Google login failed:', error);
          throw error;
        }
      },

      logout: () => {
        set({
          token: null,
          user: null,
          credentials: null,
          googleCredential: null,
          isAuthenticated: false,
        });
      },

      checkAuth: () => {
        const state = get();
        if (!state.token) {
          set({ isAuthenticated: false });
        }
      },
    }),
    {
      name: 'auth-storage',
    }
  )
);
