import { Component, inject, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import { Control, DomEvent, DomUtil, icon, Icon, latLng, Layer, Map, MapOptions, Marker, tileLayer } from 'leaflet';
import { BusinessListing, CommercialPropertyListing } from '../../../../../bizmatch-server/src/models/db.model';

@Component({
  selector: 'app-base-details',
  template: ``,
  standalone: true,
  imports: [],
})
export abstract class BaseDetailsComponent {
  // Leaflet-Map-Einstellungen
  mapOptions: MapOptions;
  mapLayers: Layer[] = [];
  mapCenter: any;
  mapZoom: number = 13;
  protected listing: BusinessListing | CommercialPropertyListing;
  protected isBrowser: boolean;
  private platformId = inject(PLATFORM_ID);

  constructor() {
    this.isBrowser = isPlatformBrowser(this.platformId);
    // Only initialize mapOptions in browser context
    if (this.isBrowser) {
      this.mapOptions = {
        layers: [
          tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; OpenStreetMap contributors',
          }),
        ],
        zoom: this.mapZoom,
        center: latLng(0, 0),
      };
    }
  }

  protected configureMap() {
    if (!this.isBrowser) {
      return; // Skip on server
    }

    const latitude = this.listing.location.latitude;
    const longitude = this.listing.location.longitude;

    if (latitude !== null && latitude !== undefined &&
      longitude !== null && longitude !== undefined) {
      this.mapCenter = latLng(latitude, longitude);

      const addressParts = [];
      if (this.listing.location.housenumber) addressParts.push(this.listing.location.housenumber);
      if (this.listing.location.street) addressParts.push(this.listing.location.street);
      if (this.listing.location.name) addressParts.push(this.listing.location.name);
      else if (this.listing.location.county) addressParts.push(this.listing.location.county);
      if (this.listing.location.state) addressParts.push(this.listing.location.state);
      if (this.listing.location.zipCode) addressParts.push(this.listing.location.zipCode);

      const fullAddress = addressParts.join(', ');

      const marker = new Marker([latitude, longitude], {
        icon: icon({
          ...Icon.Default.prototype.options,
          iconUrl: 'assets/leaflet/marker-icon.png',
          iconRetinaUrl: 'assets/leaflet/marker-icon-2x.png',
          shadowUrl: 'assets/leaflet/marker-shadow.png',
        }),
      });

      if (fullAddress) {
        marker.bindPopup(`
          <div style="padding: 8px;">
            <strong>Location:</strong><br/>
            ${fullAddress}
          </div>
        `);
      }

      this.mapLayers = [
        tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
          attribution: '&copy; OpenStreetMap contributors',
        }),
        marker
      ];
      this.mapOptions = {
        ...this.mapOptions,
        center: this.mapCenter,
        zoom: this.mapZoom,
      };
    }
  }

  onMapReady(map: Map) {
    if (!this.isBrowser) {
      return;
    }

    const addressParts = [];
    if (this.listing.location.housenumber) addressParts.push(this.listing.location.housenumber);
    if (this.listing.location.street) addressParts.push(this.listing.location.street);
    if (this.listing.location.name) addressParts.push(this.listing.location.name);
    else if (this.listing.location.county) addressParts.push(this.listing.location.county);
    if (this.listing.location.state) addressParts.push(this.listing.location.state);
    if (this.listing.location.zipCode) addressParts.push(this.listing.location.zipCode);

    if (addressParts.length > 0) {
      const addressControl = new Control({ position: 'topright' });

      addressControl.onAdd = () => {
        const container = DomUtil.create('div', 'address-control bg-white p-2 rounded shadow');
        const address = addressParts.join(', ');
        container.innerHTML = `
          <div style="max-width: 250px;">
            ${address}<br/>
            <a href="#" id="view-full-map" style="color: #2563eb; text-decoration: underline;">View larger map</a>
          </div>
        `;

        DomEvent.disableClickPropagation(container);

        const link = container.querySelector('#view-full-map') as HTMLElement;
        if (link) {
          DomEvent.on(link, 'click', (e: Event) => {
            e.preventDefault();
            this.openFullMap();
          });
        }

        return container;
      };

      addressControl.addTo(map);
    }
  }

  openFullMap() {
    if (!this.isBrowser) {
      return;
    }

    const latitude = this.listing.location.latitude;
    const longitude = this.listing.location.longitude;
    const url = `https://www.openstreetmap.org/?mlat=${latitude}&mlon=${longitude}#map=15/${latitude}/${longitude}`;

    window.open(url, '_blank');
  }
}




