import { Component } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import { KeycloakService } from 'keycloak-angular';
import { lastValueFrom } from 'rxjs';
import { BusinessListing, User } from '../../../../../../bizmatch-server/src/models/db.model';
import { KeycloakUser, MailInfo } from '../../../../../../bizmatch-server/src/models/main.model';
import { environment } from '../../../../environments/environment';
import { MessageService } from '../../../components/message/message.service';
import { ValidatedInputComponent } from '../../../components/validated-input/validated-input.component';
import { ValidatedTextareaComponent } from '../../../components/validated-textarea/validated-textarea.component';
import { ValidationMessagesService } from '../../../components/validation-messages.service';
import { HistoryService } from '../../../services/history.service';
import { ListingsService } from '../../../services/listings.service';
import { MailService } from '../../../services/mail.service';
import { SelectOptionsService } from '../../../services/select-options.service';
import { UserService } from '../../../services/user.service';
import { SharedModule } from '../../../shared/shared/shared.module';
import { map2User } from '../../../utils/utils';
@Component({
  selector: 'app-details-business-listing',
  standalone: true,
  imports: [SharedModule, ValidatedInputComponent, ValidatedTextareaComponent],
  providers: [],
  templateUrl: './details-business-listing.component.html',
  styleUrl: '../details.scss',
})
export class DetailsBusinessListingComponent {
  // listings: Array<BusinessListing>;
  responsiveOptions = [
    {
      breakpoint: '1199px',
      numVisible: 1,
      numScroll: 1,
    },
    {
      breakpoint: '991px',
      numVisible: 2,
      numScroll: 1,
    },
    {
      breakpoint: '767px',
      numVisible: 1,
      numScroll: 1,
    },
  ];
  private id: string | undefined = this.activatedRoute.snapshot.params['id'] as string | undefined;
  listing: BusinessListing;
  mailinfo: MailInfo;
  environment = environment;
  keycloakUser: KeycloakUser;
  user: User;
  listingUser: User;
  description: SafeHtml;
  private history: string[] = [];
  ts = new Date().getTime();
  env = environment;
  constructor(
    private activatedRoute: ActivatedRoute,
    private listingsService: ListingsService,
    private router: Router,
    private userService: UserService,
    public selectOptions: SelectOptionsService,
    private mailService: MailService,
    private sanitizer: DomSanitizer,
    public historyService: HistoryService,
    public keycloakService: KeycloakService,
    private validationMessagesService: ValidationMessagesService,
    private messageService: MessageService,
  ) {
    this.router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {
        this.history.push(event.urlAfterRedirects);
      }
    });
    this.mailinfo = { sender: {}, email: '', url: environment.mailinfoUrl };
  }

  async ngOnInit() {
    const token = await this.keycloakService.getToken();
    this.keycloakUser = map2User(token);
    if (this.keycloakUser) {
      this.user = await this.userService.getByMail(this.keycloakUser.email);
      this.mailinfo.sender = { name: `${this.user.firstname} ${this.user.lastname}`, email: this.user.email, phoneNumber: this.user.phoneNumber, state: this.user.companyLocation.state };
    }
    this.listing = await lastValueFrom(this.listingsService.getListingById(this.id, 'business'));
    this.listingUser = await this.userService.getByMail(this.listing.email);
    this.description = this.sanitizer.bypassSecurityTrustHtml(this.listing.description);
  }
  ngOnDestroy() {
    this.validationMessagesService.clearMessages(); // Löschen Sie alle bestehenden Validierungsnachrichten
  }
  isAdmin() {
    return this.keycloakService.getUserRoles(true).includes('ADMIN');
  }
  async mail() {
    try {
      this.mailinfo.email = this.listingUser.email;
      this.mailinfo.listing = this.listing;
      await this.mailService.mail(this.mailinfo);
      this.messageService.addMessage({ severity: 'success', text: 'Your message has been sent to the creator of the listing', duration: 3000 });
    } catch (error) {
      this.messageService.addMessage({
        severity: 'danger',
        text: 'An error occurred while sending the request',
        duration: 5000,
      });
      if (error.error && Array.isArray(error.error?.message)) {
        this.validationMessagesService.updateMessages(error.error.message);
      }
    }
  }
  get listingDetails() {
    let typeOfRealEstate = '';
    if (this.listing.realEstateIncluded) {
      typeOfRealEstate = 'Real Estate Included';
    } else if (this.listing.leasedLocation) {
      typeOfRealEstate = 'Leased Location';
    } else if (this.listing.franchiseResale) {
      typeOfRealEstate = 'Franchise Re-Sale';
    }
    return [
      { label: 'Category', value: this.selectOptions.getBusiness(this.listing.type) },
      { label: 'Located in', value: `${this.listing.location.city}, ${this.selectOptions.getState(this.listing.location.state)}` },
      { label: 'Asking Price', value: `$${this.listing.price?.toLocaleString()}` },
      { label: 'Sales revenue', value: `$${this.listing.salesRevenue?.toLocaleString()}` },
      { label: 'Cash flow', value: `$${this.listing.cashFlow?.toLocaleString()}` },
      { label: 'Type of Real Estate', value: typeOfRealEstate },
      { label: 'Employees', value: this.listing.employees },
      { label: 'Established since', value: this.listing.established },
      { label: 'Support & Training', value: this.listing.supportAndTraining },
      { label: 'Reason for Sale', value: this.listing.reasonForSale },
      { label: 'Broker licensing', value: this.listing.brokerLicencing },
    ];
  }
}
