import { Component, EventEmitter, Input, Output, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { firstValueFrom } from 'rxjs';
import { GeocodingService, GeocodingResult } from '../../services/geocoding/geocoding.service';

@Component({
  selector: 'app-location-picker',
  standalone: true,
  imports: [CommonModule, FormsModule],
  template: `
    <div class="location-picker">
      <div class="location-header">
        <h4>📍 Seletor de Localização</h4>
        <button 
          class="current-location-btn"
          (click)="getCurrentLocation()"
          [disabled]="loading"
        >
          <i class="fas fa-crosshairs"></i>
          {{ loading ? 'Obtendo...' : 'Minha Localização' }}
        </button>
      </div>

      <!-- Input manual de coordenadas -->
      <div class="coordinates-input">
        <div class="input-group">
          <label>Latitude:</label>
          <input 
            type="number" 
            [(ngModel)]="latitude" 
            (blur)="onCoordinateChange()"
            step="0.000001"
            placeholder="-23.550520"
          />
        </div>
        <div class="input-group">
          <label>Longitude:</label>
          <input 
            type="number" 
            [(ngModel)]="longitude" 
            (blur)="onCoordinateChange()"
            step="0.000001"
            placeholder="-46.633308"
          />
        </div>
      </div>

      <!-- Resultado do endereço -->
      <div class="address-result" *ngIf="result">
        <div class="address-card">
          <div class="address-header">
            <i class="fas fa-map-marker-alt"></i>
            <span>Endereço Encontrado</span>
          </div>
          
          <div class="address-details">
            <div class="full-address">{{ result.formattedAddress }}</div>
            
            <div class="address-breakdown" *ngIf="showDetails">
              <div class="detail-item" *ngIf="result.city">
                <strong>Cidade:</strong> {{ result.city }}
              </div>
              <div class="detail-item" *ngIf="result.state">
                <strong>Estado:</strong> {{ result.state }}
              </div>
              <div class="detail-item" *ngIf="result.country">
                <strong>País:</strong> {{ result.country }}
              </div>
              <div class="detail-item" *ngIf="result.postalCode">
                <strong>CEP:</strong> {{ result.postalCode }}
              </div>
              <div class="detail-item" *ngIf="result.placeId">
                <strong>Place ID:</strong> {{ result.placeId }}
              </div>
            </div>
          </div>
          
          <div class="address-actions">
            <button 
              class="toggle-details-btn"
              (click)="showDetails = !showDetails"
            >
              <i class="fas" [class.fa-chevron-down]="!showDetails" [class.fa-chevron-up]="showDetails"></i>
              {{ showDetails ? 'Menos detalhes' : 'Mais detalhes' }}
            </button>
            
            <button 
              class="use-address-btn"
              (click)="useAddress()"
            >
              <i class="fas fa-check"></i>
              Usar este endereço
            </button>
          </div>
        </div>
      </div>

      <!-- Estado de loading -->
      <div class="loading-state" *ngIf="loading">
        <div class="spinner"></div>
        <span>Buscando endereço...</span>
      </div>

      <!-- Estado de erro -->
      <div class="error-state" *ngIf="error" class="error-message">
        <i class="fas fa-exclamation-triangle"></i>
        <span>{{ error }}</span>
        <button (click)="clearError()">
          <i class="fas fa-times"></i>
        </button>
      </div>

      <!-- Exemplos de uso -->
      <div class="examples" *ngIf="!result && !loading && !error">
        <h5>💡 Exemplos de coordenadas:</h5>
        <div class="example-buttons">
          <button 
            class="example-btn"
            (click)="setExample(-23.550520, -46.633308)"
          >
            📍 São Paulo/SP
          </button>
          <button 
            class="example-btn"
            (click)="setExample(-22.906847, -43.172896)"
          >
            📍 Rio de Janeiro/RJ
          </button>
          <button 
            class="example-btn"
            (click)="setExample(-25.441105, -49.276855)"
          >
            📍 Curitiba/PR
          </button>
        </div>
      </div>
    </div>
  `,
  styles: [`
    .location-picker {
      max-width: 500px;
      margin: 0 auto;
      padding: 1rem;
      border: 1px solid var(--divider);
      border-radius: 8px;
      background: var(--surface);
    }

    .location-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 1rem;
    }

    .current-location-btn {
      display: flex;
      align-items: center;
      gap: 0.5rem;
      padding: 0.5rem 1rem;
      background: var(--primary);
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      transition: all 0.2s ease;
    }

    .current-location-btn:hover:not(:disabled) {
      background: var(--primary-dark);
    }

    .current-location-btn:disabled {
      opacity: 0.6;
      cursor: not-allowed;
    }

    .coordinates-input {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 1rem;
      margin-bottom: 1rem;
    }

    .input-group {
      display: flex;
      flex-direction: column;
      gap: 0.25rem;
    }

    .input-group label {
      font-weight: 500;
      color: var(--text-secondary);
    }

    .input-group input {
      padding: 0.5rem;
      border: 1px solid var(--divider);
      border-radius: 4px;
      background: var(--surface);
      color: var(--text-primary);
    }

    .address-card {
      background: var(--surface-variant);
      border: 1px solid var(--divider);
      border-radius: 8px;
      padding: 1rem;
      margin-bottom: 1rem;
    }

    .address-header {
      display: flex;
      align-items: center;
      gap: 0.5rem;
      margin-bottom: 0.75rem;
      color: var(--primary);
      font-weight: 600;
    }

    .full-address {
      font-size: 1rem;
      color: var(--text-primary);
      margin-bottom: 0.75rem;
      line-height: 1.4;
    }

    .address-breakdown {
      margin-bottom: 1rem;
    }

    .detail-item {
      margin-bottom: 0.25rem;
      font-size: 0.875rem;
      color: var(--text-secondary);
    }

    .address-actions {
      display: flex;
      gap: 0.5rem;
      justify-content: flex-end;
    }

    .toggle-details-btn, .use-address-btn {
      display: flex;
      align-items: center;
      gap: 0.25rem;
      padding: 0.375rem 0.75rem;
      border: 1px solid var(--divider);
      border-radius: 4px;
      background: var(--surface);
      color: var(--text-primary);
      cursor: pointer;
      transition: all 0.2s ease;
    }

    .use-address-btn {
      background: var(--primary);
      color: white;
      border-color: var(--primary);
    }

    .loading-state {
      display: flex;
      align-items: center;
      gap: 0.5rem;
      padding: 1rem;
      text-align: center;
      color: var(--text-secondary);
    }

    .spinner {
      width: 20px;
      height: 20px;
      border: 2px solid var(--divider);
      border-top: 2px solid var(--primary);
      border-radius: 50%;
      animation: spin 1s linear infinite;
    }

    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }

    .error-state {
      display: flex;
      align-items: center;
      gap: 0.5rem;
      padding: 0.75rem;
      background: #fee;
      border: 1px solid #fcc;
      border-radius: 4px;
      color: #c33;
      margin-bottom: 1rem;
    }

    .examples {
      margin-top: 1rem;
      padding-top: 1rem;
      border-top: 1px solid var(--divider);
    }

    .example-buttons {
      display: flex;
      gap: 0.5rem;
      flex-wrap: wrap;
    }

    .example-btn {
      padding: 0.375rem 0.75rem;
      background: var(--surface-variant);
      border: 1px solid var(--divider);
      border-radius: 4px;
      cursor: pointer;
      transition: all 0.2s ease;
      font-size: 0.875rem;
    }

    .example-btn:hover {
      background: var(--hover-bg);
    }
  `]
})
export class LocationPickerComponent implements OnInit {
  
  @Input() latitude: number | null = null;
  @Input() longitude: number | null = null;
  @Input() autoSearch: boolean = true;
  
  @Output() locationSelected = new EventEmitter<GeocodingResult>();
  @Output() coordinatesChanged = new EventEmitter<{latitude: number, longitude: number}>();

  result: GeocodingResult | null = null;
  loading = false;
  error: string | null = null;
  showDetails = false;

  constructor(private geocodingService: GeocodingService) {}

  ngOnInit() {
    // Se já tem coordenadas, buscar endereço automaticamente
    if (this.latitude && this.longitude && this.autoSearch) {
      this.searchAddress();
    }
  }

  /**
   * 📍 Obter localização atual do usuário
   */
  async getCurrentLocation() {
    this.loading = true;
    this.error = null;

    try {
      const position = await this.geocodingService.getCurrentLocation();
      this.latitude = position.latitude;
      this.longitude = position.longitude;
      
      this.coordinatesChanged.emit({
        latitude: this.latitude,
        longitude: this.longitude
      });
      
      await this.searchAddress();
      
    } catch (error: any) {
      this.error = error.message || 'Erro ao obter localização atual';
    } finally {
      this.loading = false;
    }
  }

  /**
   * 🔍 Buscar endereço quando coordenadas mudarem
   */
  onCoordinateChange() {
    if (this.latitude && this.longitude) {
      this.coordinatesChanged.emit({
        latitude: this.latitude,
        longitude: this.longitude
      });
      
      if (this.autoSearch) {
        this.searchAddress();
      }
    }
  }

  /**
   * 🌍 Buscar endereço pelas coordenadas
   */
  async searchAddress() {
    if (!this.latitude || !this.longitude) {
      this.error = 'Coordenadas são obrigatórias';
      return;
    }

    this.loading = true;
    this.error = null;
    this.result = null;

         try {
       const result = await firstValueFrom(this.geocodingService
         .reverseGeocode(this.latitude, this.longitude));
       
       this.result = result || null;
         
     } catch (error: any) {
      this.error = error.message || 'Erro ao buscar endereço';
    } finally {
      this.loading = false;
    }
  }

  /**
   * 📌 Definir exemplo de coordenadas
   */
  setExample(lat: number, lng: number) {
    this.latitude = lat;
    this.longitude = lng;
    this.onCoordinateChange();
  }

  /**
   * ✅ Usar endereço selecionado
   */
  useAddress() {
    if (this.result) {
      this.locationSelected.emit(this.result);
    }
  }

  /**
   * 🚫 Limpar erro
   */
  clearError() {
    this.error = null;
  }
} 