import { useAuthStore } from './auth-store';

const API_URL = process.env.NEXT_PUBLIC_API_URL;

export interface AuthResponse {
  success: boolean;
  message?: string;
  token?: string;
  resetToken?: string;
  hasActiveSubscription?: boolean;
  user?: {
    id: string;
    firstName: string;
    lastName: string;
    email: string;
    userType: string;
    profileImage?: string;
    isDentist?: boolean;
  };
  error?: string;
}

export class AuthService {
  static async register(data: {
    firstName: string;
    lastName: string;
    email: string;
    password: string;
    confirmPassword: string;
    userType?: string;
    isDentist?: boolean;
    language?: 'es' | 'en';
  }): Promise<AuthResponse> {
    try {
      const response = await fetch(`${API_URL}/api/auth/register`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
      });

      const result = await response.json();

      if (!response.ok) {
        return {
          success: false,
          error: result.error || 'Registration failed',
        };
      }

      // Store in Zustand - REMOVED for manual login flow
      // if (result.token && result.user) {
      //   useAuthStore.getState().setAuth(result.user, result.token);
      // }

      return result;
    } catch (error: any) {
      return {
        success: false,
        error: error.message || 'Network error',
      };
    }
  }

  static async login(email: string, password: string): Promise<AuthResponse> {
    try {
      const response = await fetch(`${API_URL}/api/auth/login`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ email, password }),
      });

      const result = await response.json();

      if (!response.ok) {
        return {
          success: false,
          error: result.error || 'Login failed',
        };
      }

      // Store in Zustand
      if (result.token && result.user) {
        useAuthStore.getState().setAuth(result.user, result.token, result.hasActiveSubscription);
      }

      return result;
    } catch (error: any) {
      return {
        success: false,
        error: error.message || 'Network error',
      };
    }
  }

  static async forgotPassword(email: string, language?: 'es' | 'en'): Promise<AuthResponse> {
    try {
      const response = await fetch(`${API_URL}/api/auth/forgot-password`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ email, language }),
      });

      const result = await response.json();
      return result;
    } catch (error: any) {
      return {
        success: false,
        error: error.message || 'Network error',
      };
    }
  }

  static async resetPassword(
    token: string,
    newPassword: string,
    confirmPassword: string
  ): Promise<AuthResponse> {
    try {
      const response = await fetch(`${API_URL}/api/auth/reset-password`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ token, newPassword, confirmPassword }),
      });

      const result = await response.json();
      return result;
    } catch (error: any) {
      return {
        success: false,
        error: error.message || 'Network error',
      };
    }
  }

  static async verify(token: string): Promise<AuthResponse> {
    try {
      const response = await fetch(`${API_URL}/api/auth/verify`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ token }),
      });

      const result = await response.json();
      return result;
    } catch (error: any) {
      return {
        success: false,
        error: error.message || 'Network error',
      };
    }
  }

  static logout(): void {
    useAuthStore.getState().logout();
  }

  static getToken(): string | null {
    return useAuthStore.getState().token;
  }

  static getUser() {
    return useAuthStore.getState().user;
  }

  static isAuthenticated(): boolean {
    const { token, checkTokenExpiration } = useAuthStore.getState();
    return !!token && checkTokenExpiration();
  }
}
