import { ChangeDetectorRef, Component } from '@angular/core';
import { NgOptimizedImage } from '@angular/common';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { ActivatedRoute, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { BusinessListing, CommercialPropertyListing, User, ShareByEMail, EventTypeEnum } from '../../../../../../bizmatch-server/src/models/db.model';
import { KeycloakUser, emailToDirName } from '../../../../../../bizmatch-server/src/models/main.model';
import { environment } from '../../../../environments/environment';
import { BreadcrumbItem, BreadcrumbsComponent } from '../../../components/breadcrumbs/breadcrumbs.component';
import { AuthService } from '../../../services/auth.service';
import { AuditService } from '../../../services/audit.service';
import { EMailService } from '../../../components/email/email.service';
import { MessageService } from '../../../components/message/message.service';
import { HistoryService } from '../../../services/history.service';
import { ImageService } from '../../../services/image.service';
import { ListingsService } from '../../../services/listings.service';
import { SelectOptionsService } from '../../../services/select-options.service';
import { UserService } from '../../../services/user.service';
import { SharedModule } from '../../../shared/shared/shared.module';
import { formatPhoneNumber, map2User } from '../../../utils/utils';
import { ShareButton } from 'ngx-sharebuttons/button';
import { provideShareButtonsOptions, SharerMethods, withConfig } from 'ngx-sharebuttons';
import { shareIcons } from 'ngx-sharebuttons/icons';

@Component({
  selector: 'app-details-user',
  standalone: true,
  imports: [SharedModule, BreadcrumbsComponent, NgOptimizedImage, ShareButton],
  providers: [
    provideShareButtonsOptions(
      shareIcons(),
      withConfig({
        debug: false,
        sharerMethod: SharerMethods.Anchor,
      }),
    ),
  ],
  templateUrl: './details-user.component.html',
  styleUrls: [
    '../details.scss',
    '../../../../../node_modules/ngx-sharebuttons/themes/default.scss'
  ],
})
export class DetailsUserComponent {
  private id: string | undefined = this.activatedRoute.snapshot.params['id'] as string | undefined;
  user: User;
  breadcrumbs: BreadcrumbItem[] = [
    { label: 'Home', url: '/home', icon: 'fas fa-home' },
    { label: 'Professionals', url: '/brokerListings' },
    { label: 'Profile' }
  ];
  user$: Observable<KeycloakUser>;
  keycloakUser: KeycloakUser;
  environment = environment;
  businessListings: BusinessListing[];
  commercialPropListings: CommercialPropertyListing[];
  companyOverview: SafeHtml;
  offeredServices: SafeHtml;
  ts = new Date().getTime();
  env = environment;
  emailToDirName = emailToDirName;
  formatPhoneNumber = formatPhoneNumber;
  constructor(
    private activatedRoute: ActivatedRoute,
    private router: Router,
    private userService: UserService,
    private listingsService: ListingsService,
    public selectOptions: SelectOptionsService,
    private sanitizer: DomSanitizer,
    private imageService: ImageService,
    public historyService: HistoryService,
    public authService: AuthService,
    private auditService: AuditService,
    private emailService: EMailService,
    private messageService: MessageService,
    private cdref: ChangeDetectorRef,
  ) { }

  async ngOnInit() {
    this.user = await this.userService.getById(this.id);
    const results = await Promise.all([await this.listingsService.getListingsByEmail(this.user.email, 'business'), await this.listingsService.getListingsByEmail(this.user.email, 'commercialProperty')]);
    // Zuweisen der Ergebnisse zu den Member-Variablen der Klasse
    this.businessListings = results[0];
    this.commercialPropListings = results[1] as CommercialPropertyListing[];
    const token = await this.authService.getToken();
    this.keycloakUser = map2User(token);
    this.companyOverview = this.sanitizer.bypassSecurityTrustHtml(this.user.companyOverview ? this.user.companyOverview : '');
    this.offeredServices = this.sanitizer.bypassSecurityTrustHtml(this.user.offeredServices ? this.user.offeredServices : '');
  }

  /**
   * Toggle professional favorite status
   */
  async toggleFavorite() {
    try {
      const isFavorited = this.user.favoritesForUser?.includes(this.keycloakUser.email);

      if (isFavorited) {
        // Remove from favorites
        await this.listingsService.removeFavorite(this.user.id, 'user');
        this.user.favoritesForUser = this.user.favoritesForUser.filter(
          email => email !== this.keycloakUser.email
        );
      } else {
        // Add to favorites
        await this.listingsService.addToFavorites(this.user.id, 'user');
        if (!this.user.favoritesForUser) {
          this.user.favoritesForUser = [];
        }
        this.user.favoritesForUser.push(this.keycloakUser.email);
        this.auditService.createEvent(this.user.id, 'favorite', this.keycloakUser?.email);
      }

      this.cdref.detectChanges();
    } catch (error) {
      console.error('Error toggling favorite', error);
    }
  }

  isAlreadyFavorite(): boolean {
    if (!this.keycloakUser?.email || !this.user?.favoritesForUser) return false;
    return this.user.favoritesForUser.includes(this.keycloakUser.email);
  }


  /**
   * Show email sharing modal
   */
  async showShareByEMail() {
    const result = await this.emailService.showShareByEMail({
      yourEmail: this.keycloakUser ? this.keycloakUser.email : '',
      yourName: this.keycloakUser ? `${this.keycloakUser.firstName} ${this.keycloakUser.lastName}` : '',
      recipientEmail: '',
      url: environment.mailinfoUrl,
      listingTitle: `${this.user.firstname} ${this.user.lastname} - ${this.user.companyName}`,
      id: this.user.id,
      type: 'user',
    });
    if (result) {
      this.auditService.createEvent(this.user.id, 'email', this.keycloakUser?.email, <ShareByEMail>result);
      this.messageService.addMessage({
        severity: 'success',
        text: 'Your Email has been sent',
        duration: 5000,
      });
    }
  }

  /**
   * Create audit event
   */
  createEvent(eventType: EventTypeEnum) {
    this.auditService.createEvent(this.user.id, eventType, this.keycloakUser?.email);
  }

  /**
   * Share to Facebook
   */
  shareToFacebook() {
    const url = encodeURIComponent(window.location.href);
    window.open(`https://www.facebook.com/sharer/sharer.php?u=${url}`, '_blank', 'width=600,height=400');
    this.createEvent('facebook');
  }

  /**
   * Share to Twitter/X
   */
  shareToTwitter() {
    const url = encodeURIComponent(window.location.href);
    const text = encodeURIComponent(`Check out ${this.user.firstname} ${this.user.lastname} - ${this.user.companyName}`);
    window.open(`https://twitter.com/intent/tweet?url=${url}&text=${text}`, '_blank', 'width=600,height=400');
    this.createEvent('x');
  }

  /**
   * Share to LinkedIn
   */
  shareToLinkedIn() {
    const url = encodeURIComponent(window.location.href);
    window.open(`https://www.linkedin.com/sharing/share-offsite/?url=${url}`, '_blank', 'width=600,height=400');
    this.createEvent('linkedin');
  }
}
