import { Component, NgZone } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { ActivatedRoute, Router } from '@angular/router';
import { faTimes } from '@fortawesome/free-solid-svg-icons';
import { KeycloakService } from 'keycloak-angular';
import { lastValueFrom } from 'rxjs';
import { CommercialPropertyListing, User } from '../../../../../../bizmatch-server/src/models/db.model';
import { CommercialPropertyListingCriteria, ErrorResponse, 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 { ImageService } from '../../../services/image.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-commercial-property-listing',
  standalone: true,
  imports: [SharedModule, ValidatedInputComponent, ValidatedTextareaComponent],
  providers: [],
  templateUrl: './details-commercial-property-listing.component.html',
  styleUrl: '../details.scss',
})
export class DetailsCommercialPropertyListingComponent {
  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: CommercialPropertyListing;
  criteria: CommercialPropertyListingCriteria;
  mailinfo: MailInfo;
  environment = environment;
  keycloakUser: KeycloakUser;
  user: User;
  listingUser: User;
  description: SafeHtml;
  ts = new Date().getTime();
  env = environment;
  errorResponse: ErrorResponse;
  faTimes = faTimes;
  propertyDetails = [];

  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 imageService: ImageService,
    private ngZone: NgZone,
    private validationMessagesService: ValidationMessagesService,
    private messageService: MessageService,
  ) {
    this.mailinfo = { sender: {}, email: '', url: environment.mailinfoUrl };

    // this.criteria = onChange(getCriteriaStateObject('commercialProperty'), getSessionStorageHandler);
  }

  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, 'commercialProperty'))) as CommercialPropertyListing;
    this.listingUser = await this.userService.getByMail(this.listing.email);
    this.description = this.sanitizer.bypassSecurityTrustHtml(this.listing.description);
    import('flowbite').then(flowbite => {
      flowbite.initCarousels();
    });
    this.propertyDetails = [
      { label: 'Property Category', value: this.selectOptions.getCommercialProperty(this.listing.type) },
      { label: 'Located in', value: this.selectOptions.getState(this.listing.state) },
      { label: 'City', value: this.listing.city },
      { label: 'Zip Code', value: this.listing.zipCode },
      { label: 'County', value: this.listing.county },
      { label: 'Asking Price:', value: `$${this.listing.price?.toLocaleString()}` },
    ];
    //this.initFlowbite();
  }
  ngOnDestroy() {
    this.validationMessagesService.clearMessages(); // Löschen Sie alle bestehenden Validierungsnachrichten
  }
  private initFlowbite() {
    this.ngZone.runOutsideAngular(() => {
      import('flowbite')
        .then(flowbite => {
          flowbite.initCarousels();
        })
        .catch(error => console.error('Error initializing Flowbite:', error));
    });
  }
  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);
      }
    }
  }
  containsError(fieldname: string) {
    return this.errorResponse?.fields.map(f => f.fieldname).includes(fieldname);
  }
  getImageIndices(): number[] {
    return this.listing && this.listing.imageOrder ? this.listing.imageOrder.slice(1).map((e, i) => i + 1) : [];
  }
}
