import { ChangeDetectorRef, Component } from '@angular/core';
import { CommercialPropertyListing, User } from '../../../../../../bizmatch-server/src/models/db.model';
import { ListingType } from '../../../../../../bizmatch-server/src/models/main.model';
import { ConfirmationComponent } from '../../../components/confirmation/confirmation.component';
import { ConfirmationService } from '../../../components/confirmation/confirmation.service';
import { MessageComponent } from '../../../components/message/message.component';
import { MessageService } from '../../../components/message/message.service';
import { AuthService } from '../../../services/auth.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 { map2User } from '../../../utils/utils';

@Component({
  selector: 'app-my-listing',
  standalone: true,
  imports: [SharedModule, ConfirmationComponent],
  providers: [],
  templateUrl: './my-listing.component.html',
  styleUrl: './my-listing.component.scss',
})
export class MyListingComponent {
  // Vollständige, ungefilterte Daten
  listings: Array<ListingType> = [];
  // Aktuell angezeigte (gefilterte) Daten
  myListings: Array<ListingType> = [];

  user: User;

  // VERY small filter state
  filters = {
    title: '',
    internalListingNumber: '',
    location: '',
    status: '' as '' | 'published' | 'draft',
    category: '' as '' | 'business' | 'commercialProperty', // <── NEU
  };

  constructor(
    public userService: UserService,
    private listingsService: ListingsService,
    private cdRef: ChangeDetectorRef,
    public selectOptions: SelectOptionsService,
    private messageService: MessageService,
    private confirmationService: ConfirmationService,
    private authService: AuthService,
  ) { }

  async ngOnInit() {
    const token = await this.authService.getToken();
    const keycloakUser = map2User(token);
    const email = keycloakUser.email;
    this.user = await this.userService.getByMail(email);

    const result = await Promise.all([this.listingsService.getListingsByEmail(this.user.email, 'business'), this.listingsService.getListingsByEmail(this.user.email, 'commercialProperty')]);

    this.listings = [...result[0], ...result[1]];
    this.myListings = this.listings;
  }
  private normalize(s: string | undefined | null): string {
    return (s ?? '')
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, ' ') // Kommas, Bindestriche etc. neutralisieren
      .trim()
      .replace(/\s+/g, ' '); // Mehrfach-Spaces zu einem Space
  }
  applyFilters() {
    const titleQ = this.normalize(this.filters.title);
    const locQ = this.normalize(this.filters.location);
    const intQ = this.normalize(this.filters.internalListingNumber);
    const catQ = this.filters.category; // <── NEU
    const status = this.filters.status;

    this.myListings = this.listings.filter(l => {
      const okTitle = !titleQ || this.normalize(l.title).includes(titleQ);

      const locStr = this.normalize(`${l.location?.name ? l.location.name : l.location?.county} ${l.location?.state}`);
      const okLoc = !locQ || locStr.includes(locQ);

      const ilnStr = this.normalize((l as any).internalListingNumber?.toString());
      const okInt = !intQ || ilnStr.includes(intQ);

      const okCat = !catQ || l.listingsCategory === catQ; // <── NEU

      const isDraft = !!(l as any).draft;
      const okStatus = !status || (status === 'published' && !isDraft) || (status === 'draft' && isDraft);

      return okTitle && okLoc && okInt && okCat && okStatus; // <── NEU
    });
  }

  clearFilters() {
    this.filters = { title: '', internalListingNumber: '', location: '', status: '', category: '' };
    this.myListings = this.listings;
  }

  async deleteListing(listing: ListingType) {
    if (listing.listingsCategory === 'business') {
      await this.listingsService.deleteBusinessListing(listing.id);
    } else {
      await this.listingsService.deleteCommercialPropertyListing(listing.id, (listing as CommercialPropertyListing).imagePath);
    }
    const result = await Promise.all([this.listingsService.getListingsByEmail(this.user.email, 'business'), this.listingsService.getListingsByEmail(this.user.email, 'commercialProperty')]);
    this.listings = [...result[0], ...result[1]];
    this.applyFilters(); // Filter beibehalten nach Löschen
  }

  async confirm(listing: ListingType) {
    const confirmed = await this.confirmationService.showConfirmation({ message: `Are you sure you want to delete this listing?` });
    if (confirmed) {
      // this.messageService.showMessage('Listing has been deleted');
      this.deleteListing(listing);
    }
  }
}
