import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, catchError, map, Observable, of, tap } from 'rxjs';
import { Router } from '@angular/router';
interface AuthResponse {
  status: string;
  message?: string;
  user?: any;
  redirect?: string;
  isAdmin?: boolean;
  isUser?: boolean;
}
@Injectable({
  providedIn: 'root',
})
export class AuthService {
  private loginApiUrl = 'https://infoways.in/funtelapi/login.php';
  private getUserApiUrl = 'https://infoways.in/funtelapi/get_user.php';
  private logoutUrl = 'https://infoways.in/funtelapi/logout.php';
  private adminLoginApiUrl = 'https://infoways.in/funtelapi/admin/login.php';
  private checkAuthUrl = 'https://infoways.in/funtelapi/admin/check-auth.php';
  private checkUserAuthUrl = 'https://infoways.in/funtelapi/check-auth.php';
  private sendOtpUrl = 'https://infoways.in/funtelapi/send_otp.php';
  private verifyOtpUrl = 'https://infoways.in/funtelapi/verify_otp.php';
  private checkUserExistsUrl = 'https://infoways.in/funtelapi/check_user_exists.php';
  private registerAndLoginUrl = 'https://infoways.in/funtelapi/register_and_login.php';

private currentUserId: number | null = null;
private currentUserSubject = new BehaviorSubject<any>(null);
  currentUser$ = this.currentUserSubject.asObservable();
  public redirectUrl: string | null = null;
  private lastUpdateTime = 0;
private readonly DATA_FRESHNESS_THRESHOLD = 30000;

  
  constructor(private http: HttpClient, private router:Router) {}

  login(username: string, password: string): Observable<any> {
    return this.http.post<AuthResponse>(
      this.loginApiUrl,
      { username, password },
      { withCredentials: true }
    );
  }

 checkUserExists(mobile: string): Observable<any> {
    return this.http.post(`${this.checkUserExistsUrl}`, { mobile })
      .pipe(
        map((response: any) => {
          return response;
        }),
        catchError((error) => {
          console.error('Error checking user existence:', error);
          return of({ exists: false, error: true });
        })
      );
  }

  registerAndLogin(userData: any): Observable<any> {
    return this.http.post(`${this.registerAndLoginUrl}`, userData)
      .pipe(
        map((response: any) => {
          if (response.status === 'success') {
            // Store user data if needed
            this.currentUserSubject.next(response.user);
            this.setCurrentUser(response.user.id);
          }
          return response;
        }),
        catchError((error) => {
          console.error('Registration error:', error);
          return of({ status: 'error', error: 'Registration failed' });
        })
      );
  }
  
logout(): Observable<any> {
  return this.http.get<any>(
    'https://infoways.in/funtelapi/logout.php', 
    { withCredentials: true }
  ).pipe(
    tap(() => {
      // Clear all local state
      this.currentUserSubject.next(null);
      this.currentUser = null;
      this.currentUserId = null;
      
      // Redirect to login page
      this.router.navigate(['/login']);
    }),
    catchError(err => {
      console.error('Logout failed:', err);
      // Even if API fails, clear local state
      this.currentUserSubject.next(null);
      this.currentUser = null;
      this.currentUserId = null;
      return of(null);
    })
  );
}

  getCurrentUserValue(): any {
  return this.currentUserSubject.value;
}
googleLogin(googleUser: any): Observable<any> {
    return this.http.post<any>('YOUR_BACKEND_API_URL/auth/google', googleUser);
  }
  // Get user details from server (uses HTTP-only cookie)
getUserDetails(): Observable<any> {
  return this.http.get(this.getUserApiUrl, { withCredentials: true }).pipe(
    catchError(() => of({ status: 'error' }))
    
  );
}
updateCurrentUser(user: any): void {
  this.currentUserSubject.next(user);
}

  isLoggedIn(): Observable<boolean> {
    return this.getUserDetails().pipe(
      map(response => response.status === 'success'),
      catchError(() => of(false))
    );
  }

  isAdmin(): Observable<boolean> {
    return this.verifyAuth().pipe(
      map(response => response.isAdmin === true)
    );
  }

  private verifyAuth(): Observable<any> {
    return this.http.get<any>(this.checkAuthUrl, { withCredentials: true }).pipe(
      catchError(() => of({ status: 'error' }))
    );
  }
  adminLogin(credentials: {email: string, password: string}): Observable<any> {
  return this.http.post<any>(this.adminLoginApiUrl, credentials, { withCredentials: true }).pipe(
    tap(response => {
      if (response.status === 'success') {
       
        const redirectPath = response.redirect.replace(/\\\//g, '/');
        this.router.navigate([redirectPath]);
      }
    })
  );
}
userLogin(credentials: {email: string, password: string}): Observable<any> {
  return this.http.post<any>(this.loginApiUrl, credentials, { withCredentials: true }).pipe(
    tap(response => {
      if (response.status === 'success') {
        this.currentUserSubject.next(response.user);
        sessionStorage.setItem('userId', response.user.id); // Add this line
        const redirectPath = response.redirect.replace(/\\\//g, '/');
        this.router.navigate([redirectPath]);
      }
    })
  );
}

isUser(): Observable<boolean> {
    return this.verifyUserAuth().pipe(
      map(response => response.isUser === true)
    );
  }

  private verifyUserAuth(): Observable<any> {
    return this.http.get<any>(this.checkUserAuthUrl, { withCredentials: true }).pipe(
      catchError(() => of({ status: 'error' }))
    );
  }
 setCurrentUser(id: number | null): void {
  this.currentUserId = id;
}

getCurrentUserId(): number | null {
  // return this.currentUserId;
  
  return this.currentUserSubject.value?.id ?? this.currentUserId;
  
}

verifyTokenAndFetchUser(): Observable<any> {
  return this.http.get<any>('https://infoways.in/funtelapi/check-auth.php', { withCredentials: true }).pipe(
    tap((res) => {
      if (res.status === 'success') {
        const user = res.user;
        this.currentUserSubject.next(user);
        this.setCurrentUser(user.id); // ✅ make sure currentUserId is set too
      }
    }),
    catchError(() => {
      this.currentUserSubject.next(null);
      this.setCurrentUser(null);
      return of(null);
    })
  );
}
private currentUser: any = null;

getCurrentUser(): Observable<any> {
    if (this.currentUser) {
      return of({ status: 'success', user: this.currentUser });
    }

    return this.http.get<any>(this.getUserApiUrl, {
      withCredentials: true,
    }).pipe(
      tap((res) => {
        if (res.status === 'success') {
          this.currentUser = res.user;
        }
      }),
      catchError(() => of({ status: 'error' }))
    );
  }
initializeAuthState(): Promise<boolean> {
  return new Promise((resolve) => {
    this.getUserDetails().subscribe({
      next: (response) => {
        if (response.status === 'success') {
          this.currentUserSubject.next(response.user);
          this.setCurrentUser(response.user.id);
          resolve(true);
        } else {
          this.clearUser();
          resolve(false);
        }
      },
      error: () => {
        this.clearUser();
        resolve(false);
      }
    });
  });
}
private clearUser(): void {
  this.currentUserSubject.next(null);
  this.setCurrentUser(null);
  this.currentUser = null;
}

checkInitialAuthState(): void {
    this.getUserDetails().subscribe({
      next: (response) => {
        if (response.status === 'success') {
          this.currentUserSubject.next(response.user);
        } else {
          this.currentUserSubject.next(null);
        }
      },
      error: () => this.currentUserSubject.next(null)
    });
  }

sendOtp(mobile: string): Observable<any> {
  return this.http.post(`${this.sendOtpUrl}`, { mobile })
    .pipe(
      map((response: any) => {
        if (response.status === 'success') {
          // For development, OTP will be in response
          if (response.otp) {
            console.log('OTP for development:', response.otp);
            // Store in localStorage for auto-fill
            // localStorage.setItem('debug_otp', response.otp);
            // localStorage.setItem('debug_mobile', mobile);
          }
          return response;
        } else {
          throw new Error(response.error);
        }
      })
    );
}

registerNewUser(userData: any): Observable<any> {
  return this.http.post('https://infoways.in/funtelapi/register_new_user.php', userData)
    .pipe(
      map((response: any) => {
        if (response.status === 'success') {
          this.currentUserSubject.next(response.user);
          this.setCurrentUser(response.user.id);
        }
        return response;
      })
    );
}

verifyOtp(mobile: string, otp: string): Observable<any> {
  return this.http.post(`${this.verifyOtpUrl}`, { mobile, otp }).pipe(
    map((response: any) => {
      if (response.status === 'success') {
        return response;
      } else {
        throw new Error(response.error);
      }
    })
  );
}
}
