//OrderService
import { HttpHeaders, HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { CartItemViewModel, CartViewModel, Product, WishlistItemViewModel, WishlistViewModel } from '../shared/order';
import { BehaviorSubject, map, Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class OrderService {
  private cartItemsCountSource = new BehaviorSubject<number>(0);
  cartItemsCount = this.cartItemsCountSource.asObservable();

  private wishlistItemsCountSource = new BehaviorSubject<number>(0);
  wishlistItemsCount = this.wishlistItemsCountSource.asObservable();
  
  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    })
  };
  
  constructor(private http: HttpClient) {}
  apiUrl: string = "https://localhost:7185/api/Order";

  //navbar count
  updateCartCount(count: number) {
    this.cartItemsCountSource.next(count);
  }

  loadCartItems(): void {
    this.getCartItems().subscribe({
      next: (items) => {
        const totalCount = items.reduce((sum, item) => sum + item.quantity, 0);
        this.updateCartCount(totalCount);
      },
      error: (err) => {
        console.error('Error loading cart items', err);
      }
    });
  }

  updateWishlistCount(count: number) {
    this.wishlistItemsCountSource.next(count);
  }

  loadWishlistItems(): void {
    this.getWishlistItems().subscribe({
      next: (items) => {
        this.updateWishlistCount(items.length);
      },
      error: (err) => {
        console.error('Error loading wishlist items', err);
      }
    });
  }

  //products
  getAllProducts(): Observable<Product[]> {
    return this.http.get<Product[]>(`${this.apiUrl}/GetAllProducts`, this.httpOptions);
  }

  getProductById(product_id: number): Observable<Product> {
    return this.http.get<Product>(`${this.apiUrl}/GetProductById/${product_id}`, this.httpOptions);
  }

  //cart
  getCartItems(): Observable<CartItemViewModel[]> {
    const token = localStorage.getItem('token');
    console.log('Retrieved token from localStorage:', token); 

    const httpOptionsWithAuth = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      })
    };

    return this.http.get<CartItemViewModel[]>(`${this.apiUrl}/GetCart`, httpOptionsWithAuth);
  }

  addToCart(cartViewModel: { product_ID: number; quantity: number; size: string }): Observable<any> {
    const token = localStorage.getItem('token');
    console.log('Retrieved token from localStorage:', token); 

    const httpOptionsWithAuth = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      })
    };

    return this.http.post<any>(`${this.apiUrl}/AddToCart`, cartViewModel, httpOptionsWithAuth);
  }

  updateCart(cartViewModel: CartViewModel): Observable<any> {
    const token = localStorage.getItem('token');
    console.log('Retrieved token from localStorage:', token); 

    const httpOptionsWithAuth = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      })
    };

    return this.http.put<any>(`${this.apiUrl}/UpdateCart`, cartViewModel, httpOptionsWithAuth);
  }

  removeFromCart(productId: number): Observable<any> {
    const token = localStorage.getItem('token');
    const httpOptionsWithAuth = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      })
    };
    return this.http.delete<any>(`${this.apiUrl}/RemoveFromCart/${productId}`, httpOptionsWithAuth);
  }

  //wishlist
  getWishlistItems(): Observable<WishlistItemViewModel[]> {
    const token = localStorage.getItem('token');
    const httpOptionsWithAuth = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      })
    };
    return this.http.get<WishlistItemViewModel[]>(`${this.apiUrl}/GetWishlist`, httpOptionsWithAuth);
  }

  addToWishlist(wishlistViewModel: WishlistViewModel): Observable<any> {
    const token = localStorage.getItem('token');
    const httpOptionsWithAuth = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      })
    };
    return this.http.post<any>(`${this.apiUrl}/AddToWishlist`, wishlistViewModel, httpOptionsWithAuth);
  }

  removeFromWishlist(productId: number): Observable<any> {
    const token = localStorage.getItem('token');
    const httpOptionsWithAuth = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      })
    };
    return this.http.delete<any>(`${this.apiUrl}/RemoveFromWishlist/${productId}`, httpOptionsWithAuth);
  }

  moveFromWishlistToCart(product_ID: number): Observable<any> {
    const token = localStorage.getItem('token');
    const httpOptionsWithAuth = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      }),
      responseType: 'text' as 'json' // Specify response type as text
    };
    return this.http.post<any>(`${this.apiUrl}/MoveFromWishlistToCart`, { product_ID, quantity: 1 }, httpOptionsWithAuth);
  }

  //payfast
  getTotalAmount(): Observable<number> {
    return this.getCartItems().pipe(
      map(items => items.reduce((sum, item) => sum + (item.unit_Price * item.quantity), 0))
    );
  }

  getUserData(): any {
    // Replace this with your actual implementation to get user data
    return {
      email: 'user@example.com'
    };
  }
}