// Questo file fa parte di MyTown.
// MyTown è software libero: puoi ridistribuirlo e/o modificarlo secondo
// i termini della GNU Affero General Public License come pubblicata dalla
// Free Software Foundation, versione 3.
// Distribuito senza ALCUNA GARANZIA; vedi la GNU AGPL v3 per i dettagli.
// Copyright (C) Kondor Consulting & Services S.r.l.
// SPDX-License-Identifier: AGPL-3.0-or-later

import { Component, OnInit, EventEmitter, Output, Input } from '@angular/core';
import { Router } from '@angular/router';
import { ActivatedRoute } from "@angular/router";
import { Location } from '@angular/common';
import { Subscription } from 'rxjs';
import { TranslateService } from '@ngx-translate/core';

import { ConfigService } from 'src/app/providers/config.service';
import { CartService } from 'src/app/providers/cart.service';
import { ProdService } from 'src/app/providers/prod.service';
import { BizReviewsService } from 'src/app/providers/biz-reviews.service';
import { Review } from 'src/models/biz-appointments/review.model';

@Component({
  selector: 'app-product-detail',
  templateUrl: './product-detail.component.html',
  styleUrls: ['./product-detail.component.scss'],
  standalone: false,
})

export class ProductDetailComponent  implements OnInit {

  constructor(    
      private router: Router,
      private activatedRoute: ActivatedRoute,
      private prodService: ProdService,
      private cartService: CartService,
      private location: Location,
      private config: ConfigService,
      private translate: TranslateService,
      private configService: ConfigService,
      private reviewsService: BizReviewsService,
  ){}
  
  // VARIABILI
  cmp_id: number = 0;
  prt_id: number = 0;
  comuni: any[] = [];
  comuniCache: Map<string, any[]> = new Map(); // Cache per comuni filtrati
  lstFilter: any[] = [];
  objav: any;
  av: any;
  objcomune: any;
  filterTypewine:any;
  lst_typeproducts: any[] = []; 
  type: any;
  filter: any = {};
  onlineshopImageUrl = "";
  product : any = {id: 0, cmp_id: 0, title:"", tpw_id: 0 , shortdescription:"", description:"", photo: [{prph_path_photo_lg: ""}],
                   cost: null, price: null, amount: null, productionyear: null, isavailable: null, codicefiscale: "", note:""};
  availability: any[] = [{name:'Disponibile',val: true},{name:'Non disponibile',val: false}];
  // Recensioni del negozio (sorgente ORDINE), pubbliche: visibili a tutti nel dettaglio prodotto.
  reviews: Review[] = [];
  stars = [1, 2, 3, 4, 5];
  responsiveOptions: any[] = [
    { breakpoint: '1024px', numVisible: 5 },
    { breakpoint: '768px', numVisible: 3 },
    { breakpoint: '560px', numVisible: 1 }
  ];

  //----------INIZIALIZZAZIONE PAGINA------------------------------------

  paramsSubscription?: Subscription;
  ngOnInit(): void {
    this.onlineshopImageUrl = this.config.onlineshopImageUrl;
    this.paramsSubscription = this.activatedRoute.params.subscribe((params) => {
      if (params['prt_id']) this.prt_id = +params['prt_id'];
			if (params['cmp_id']) this.cmp_id = +params['cmp_id'];
      if (params['id']) this.product.id = +params['id'];
      });
  }

  ionViewWillEnter(){
    this.resetFilter();
    this.resetFilterTypeWine();
    this.prodService.get_typewine(this.filterTypewine).subscribe(res => {
        this.lst_typeproducts = res;
        this.getPrd(this.product.id);
      });    
  }

  ngOnDestroy() {
		this.paramsSubscription?.unsubscribe();
	}


  // RESET FILTERS
  resetFilterTypeWine(){
    this.filterTypewine = {};
    this.filterTypewine.tpw_cmp_id = this.cmp_id;
    this.filterTypewine.pagina = 1;
    this.filterTypewine.righePagina = 99999;
    this.filterTypewine.orderBy = 'tpw_name';
  }
  resetFilter() {
    this.filter = {};
    this.filter.pagina = 1;
    this.filter.righePagina = 99999;
    this.filter.orderBy = 'prd_title';
    this.filter.type_wine = -1;
    this.filter.price_from = null;
    this.filter.price_to = null;
    this.lstFilter = [];
  }

 // GET PRD
  getPrd(prd_id: number){

    let lang='it';
    this.prodService.getProductDetails(this.cmp_id, lang, prd_id).subscribe(res => {
      this.product = res;
      this.type = this.lst_typeproducts.find(x => x.tpw_id === this.product.tpw_id);
      this.objav = this.availability.find(x => x.val === this.product.isavailable);
      this.getComune(this.product.codicefiscale);
      this.getSeverity();
    });
    this.loadShopReviews();
  }

  // Recensioni pubbliche del negozio (sorgente ORDINE), visibili a tutti.
  loadShopReviews() {
    if (!this.cmp_id) return;
    this.reviewsService.getReviews(this.cmp_id, null, 20, 0, 'ORDINE').subscribe({
      next: (res) => (this.reviews = res?.list || []),
      error: () => (this.reviews = []),
    });
  }

  reviewerName(r: Review): string {
    const n = `${r.client_firstname || ''} ${r.client_lastname || ''}`.trim();
    return n || 'Cliente';
  }


  // AZIONI
  addPrdCart(prd: any){
    prd.cmp_id = this.cmp_id;
    prd.title.trim();
    prd.tpw_id = this.type.tpw_id;
    prd.isavailable = this.objav.val;
    prd.codicefiscale = this.objcomune.codicefiscale;
    prd.qnt = 1;
    this.cartService.addPrdCart(prd).subscribe(() => {
      this.router.navigate(['/portale', this.prt_id, 'company', this.cmp_id, 'service', 'onlineshop', 'cart']);
    });
  }

  addPrdWishlist(prd: any){
    prd.cmp_id = this.cmp_id;
    this.prodService.addPrdWishlist(this.cmp_id, prd.id).subscribe(() => {
      this.router.navigate(['/portale', this.prt_id, 'company', this.cmp_id, 'service', 'onlineshop', 'products']);
    });
  }

  removePrdWishlist(prd: any){
    this.prodService.removePrdWishlist(prd.id).subscribe(() => {
      this.router.navigate(['/portale', this.prt_id, 'company', this.cmp_id, 'service', 'onlineshop', 'products']);
    });
  }

  // COMUNI
	onFilterChangeCom(event: any) {
		const filterValue = event.filter || '';
		if (filterValue.length >= 3 || filterValue === '') {
			this.getComuni(filterValue);
		}
	}
  getComuni(filterValue: string) {
		this.cartService.getComuniSelect(filterValue).subscribe((res: any) => {
			if (res) {
				this.comuni = res;
			}
		});
	}
  getComune(filterValue: string){
    this.cartService.getComuniSelect(filterValue).subscribe((res: any) => {
			if (res) {
        this.comuni = res;
				this.objcomune = this.comuni.find(x => x.codicefiscale === this.product.codicefiscale);
			}
		});
  }
    
  // BADGE
  getSeverity() {
    if(this.product.amount <= 0){
      this.av = {text: 'non disponibile', status: 'danger'};

    }
    if(this.product.amount <= 10){
      this.av = {text: 'ultimi pezzi', status: 'warning'};

    }
    if(this.product.amount > 10){
      this.av = {text: 'disponibile', status: 'success'};

    }
  }


  // GALLERIA FOTO
  indexImg:number = 0;

  prevImage(){
    let lgt = this.product.photo.length -1;
    if(this.indexImg > 0 && this.indexImg <= lgt){
      this.indexImg--;
    }else{
        this.indexImg = 0;
    }
  }
  nextImage(){
    let lgt = this.product.photo.length -1;
    if(this.indexImg >=0 && this.indexImg < lgt){
      this.indexImg++;
    }else{
      this.indexImg == lgt;
    }
  }


  // INDIRIZZAMENTI
  share(){

  }
  goBack(): void{
    this.location.back();
  }

}
