import { Component, computed, inject, input } from '@angular/core';
import { CountryResource } from '@isa/crm/data-access';
import { Address } from './types';

@Component({
  selector: 'shared-address',
  standalone: true,
  template: `
    @if (address(); as a) {
      <div class="flex flex-col" data-what="address-display">
        @if (careOfLine()) {
          <div data-which="care-of-line">
            {{ careOfLine() }}
          </div>
        }
        @if (streetLine()) {
          <div data-which="street-line">
            {{ streetLine() }}
          </div>
        }
        @if (a.info) {
          <div data-which="info">
            {{ a.info }}
          </div>
        }
        @if (cityLine()) {
          <div data-which="city-line">
            {{ cityLine() }}
          </div>
        }
      </div>
    }
  `,
})
export class AddressComponent {
  #countryResource = inject(CountryResource);

  address = input<Address>();

  careOfLine = computed(() => {
    const a = this.address();
    if (!a || !a.careOf) return '';
    return `c/o ${a.careOf}`;
  });

  streetLine = computed(() => {
    const a = this.address();
    if (!a) return '';

    const parts: string[] = [];
    if (a.street) parts.push(a.street);
    if (a.streetNumber) parts.push(a.streetNumber);
    if (a.apartment) parts.push(a.apartment);

    return parts.join(' ');
  });

  cityLine = computed(() => {
    const a = this.address();
    if (!a) return '';

    const parts: string[] = [];
    if (a.zipCode) parts.push(a.zipCode);
    if (a.city) parts.push(a.city);

    const baseLine = parts.join(' ');

    // Display country only if it exists and is not Germany
    if (a.country && a.country !== 'DEU') {
      const countryName = this.#getCountryName(a.country);
      return baseLine ? `${baseLine}, ${countryName}` : countryName;
    }

    return baseLine;
  });

  #getCountryName(countryCode: string): string {
    const countries = this.#countryResource.resource.value();
    if (!countries || !Array.isArray(countries)) return countryCode;

    const country = countries.find((c) => c.isO3166_A_3 === countryCode);
    return country?.name || countryCode;
  }
}
