// src/app/machines/machine-details/machine-details.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
import { MachineService, Machine } from '../machine.service';
import { ProductService, Product } from '../../products/product.service';
import { Subscription } from 'rxjs';
import { environment } from '@environments/environment';

interface Slot {
  name: string;
  enabled: boolean;
  units: number;
  price: string | number;
  product: Product | null;
}

interface VendingRow {
  name: string;
  id: string;
  slots: Slot[];
}

@Component({
  selector: 'app-machine-details',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './machine-details.component.html',
  styleUrl: './machine-details.component.scss'
})
export class MachineDetailsComponent implements OnInit, OnDestroy {
  machine: Machine = {
    machine_id: '',
    machine_model: '',
    machine_type: '',
    client_id: 0,
    client_name: '',
    branch_id: '',
    branch_name: '',
    operation_status: '',
    connection_status: ''
  };

  vendingRows: VendingRow[] = ['A', 'B', 'C', 'D', 'E', 'F'].map(rowId => ({
    name: `Row ${rowId}`,
    id: rowId,
    slots: Array.from({ length: 10 }, (_, i) => ({
      name: `${rowId}${i + 1}`,
      enabled: true,
      units: 0,
      price: 'N/A',
      product: null
    }))
  }));

  products: Product[] = [];
  filteredProducts: Product[] = [];
  searchTerm = '';
  showProductSelector = false;
  selectedSlot: Slot | null = null;
  selectedRow: VendingRow | null = null;
  selectedProduct: Product | null = null;
  productQuantity = 1;
  
  private subscriptions: Subscription[] = [];
  errorMessage: string | null = null;
  isLoading = false;

  // Track image loading errors
  imageLoadErrors = new Set<string>();

  constructor(
    private machineService: MachineService,
    private productService: ProductService,
    private router: Router,
    private route: ActivatedRoute
  ) { }

  ngOnInit() {
    this.loadProducts();
    this.loadMachineData();
  }

  ngOnDestroy() {
    this.subscriptions.forEach(sub => sub.unsubscribe());
  }

  /**
   * Load machine data from route or service
   */
  loadMachineData(): void {
    const machineId = this.route.snapshot.paramMap.get('id');

    if (machineId) {
      this.isLoading = true;
      this.machineService.getMachineById(Number(machineId)).subscribe({
        next: (fetchedMachine) => {
          if (fetchedMachine?.machine_id) {
            this.machine = fetchedMachine;
            this.machineService.setSelectedMachine(fetchedMachine);
            this.loadVendingState(fetchedMachine.machine_id);
            this.errorMessage = null;
          } else {
            console.warn('Could not find machine with ID:', machineId);
            this.errorMessage = 'Machine not found. Please select a machine from the list.';
            this.loadFallbackMachine();
          }
          this.isLoading = false;
        },
        error: (error) => {
          console.error('Error fetching machine:', error);
          this.errorMessage = 'Error loading machine details. Please try again.';
          this.isLoading = false;
          this.loadFallbackMachine();
        }
      });
    } else {
      this.loadFallbackMachine();
    }
  }

  /**
   * Fallback to selected machine from service
   */
  private loadFallbackMachine(): void {
    const sub = this.machineService.selectedMachine$.subscribe(machine => {
      if (machine?.machine_id) {
        this.machine = machine;
        this.loadVendingState(machine.machine_id);
        this.router.navigate(['/machines', machine.id], {
          replaceUrl: true,
          skipLocationChange: false
        });
        this.errorMessage = null;
      } else {
        console.warn('No machine selected and no ID in route');
        this.errorMessage = 'No machine selected. Please select a machine from the list.';
      }
    });
    this.subscriptions.push(sub);
  }

  /**
   * Load vending state for machine
   */
  loadVendingState(machineId: string): void {
    this.machineService.getMachineVendingState(machineId).subscribe({
      next: (response) => {
        if (response?.vendingRows) {
          this.updateSlotsFromMachine(response.vendingRows);
        }
      },
      error: (error) => console.error('Error loading vending state:', error)
    });
  }

  /**
   * Update local slots with data from backend
   */
  updateSlotsFromMachine(machineSlots: any[]): void {
    if (!machineSlots?.length) return;

    machineSlots.forEach(rowData => {
      const rowIndex = this.vendingRows.findIndex(r => r.id === rowData.rowId);
      if (rowIndex !== -1 && rowData.slots) {
        rowData.slots.forEach((slotData: any) => {
          const slotIndex = this.vendingRows[rowIndex].slots.findIndex(
            s => s.name === slotData.name
          );
          if (slotIndex !== -1) {
            const slot = this.vendingRows[rowIndex].slots[slotIndex];
            slot.enabled = slotData.enabled;
            slot.units = slotData.units;
            slot.price = slotData.price;
            if (slotData.productId) {
              const product = this.products.find(p => p.product_id === slotData.productId);
              if (product) {
                slot.product = product;
              }
            }
          }
        });
      }
    });
  }

  /**
   * Load all products
   */
  loadProducts(): void {
    this.productService.getProducts().subscribe({
      next: (data) => {
        this.products = data;
        if (this.machine?.machine_id) {
          this.loadVendingState(this.machine.machine_id);
        }
      },
      error: (error) => console.error('Error loading products:', error)
    });
  }

  /**
   * Get full image URL for a product
   */
  getImageUrl(imagePath: string | null | undefined): string {
    if (!imagePath) {
      return '';
    }
    
    // Remove leading slash if present
    const cleanPath = imagePath.startsWith('/') ? imagePath.substring(1) : imagePath;
    
    return `${environment.apiUrl}/${cleanPath}`;
  }

  /**
   * Check if image has a valid URL
   */
  hasValidImage(imagePath: string | null | undefined): boolean {
    if (!imagePath) return false;
    
    const imageUrl = this.getImageUrl(imagePath);
    return imageUrl !== '' && !this.imageLoadErrors.has(imageUrl);
  }

  /**
   * Handle image loading errors
   */
  onImageError(event: any, imagePath: string | null | undefined): void {
    if (imagePath) {
      const imageUrl = this.getImageUrl(imagePath);
      console.error('Image failed to load:', imageUrl);
      this.imageLoadErrors.add(imageUrl);
      
      // Hide the image by setting display to none
      event.target.style.display = 'none';
    }
  }

  /**
   * Toggle slot enabled/disabled status
   */
  toggleSlotStatus(row: VendingRow, slot: Slot, event: MouseEvent): void {
    event.stopPropagation();
    slot.enabled = !slot.enabled;
  }

  /**
   * Open product selector modal
   */
  openProductSelector(row: VendingRow, slot: Slot, event: Event): void {
    if (!slot.enabled) return;

    event.stopPropagation();
    this.selectedRow = row;
    this.selectedSlot = slot;
    this.showProductSelector = true;
    this.filteredProducts = [...this.products];

    // Reset selection states
    this.filteredProducts.forEach(p => p.selected = false);

    // Pre-select product if slot has one
    if (slot.product) {
      const existingProduct = this.filteredProducts.find(
        p => p.product_id === slot.product?.product_id
      );
      if (existingProduct) {
        existingProduct.selected = true;
        this.selectedProduct = existingProduct;
        this.productQuantity = slot.units || 1;
      }
    } else {
      this.selectedProduct = null;
      this.productQuantity = 1;
    }

    this.searchTerm = '';
    this.filterProducts();
  }

  /**
   * Close product selector modal
   */
  closeProductSelector(): void {
    this.showProductSelector = false;
    this.selectedRow = null;
    this.selectedSlot = null;
    this.selectedProduct = null;
    this.productQuantity = 1;
  }

  /**
   * Filter products based on search term
   */
  filterProducts(): void {
    if (!this.searchTerm.trim()) {
      this.filteredProducts = [...this.products];
      if (this.selectedProduct) {
        const selectedProduct = this.filteredProducts.find(
          p => p.product_id === this.selectedProduct?.product_id
        );
        if (selectedProduct) selectedProduct.selected = true;
      }
      return;
    }

    const term = this.searchTerm.toLowerCase().trim();
    this.filteredProducts = this.products.filter(product =>
      product.product_name.toLowerCase().includes(term) ||
      product.product_id?.toString().includes(term) ||
      (product.category && product.category.toLowerCase().includes(term))
    );

    if (this.selectedProduct) {
      const selectedProduct = this.filteredProducts.find(
        p => p.product_id === this.selectedProduct?.product_id
      );
      if (selectedProduct) selectedProduct.selected = true;
    }
  }

  /**
   * Handle product selection change
   */
  onProductSelectionChange(product: Product): void {
    this.filteredProducts.forEach(p => p.selected = false);
    product.selected = true;
    this.selectedProduct = product;

    // Pre-fill quantity if same product is already in slot
    if (this.selectedSlot?.product?.product_id === product.product_id) {
      this.productQuantity = this.selectedSlot.units || 1;
    } else {
      this.productQuantity = 1;
    }
  }

  /**
   * Increase product quantity
   */
  increaseQuantity(): void {
    this.productQuantity++;
  }

  /**
   * Decrease product quantity
   */
  decreaseQuantity(): void {
    if (this.productQuantity > 1) {
      this.productQuantity--;
    }
  }

  /**
   * Set quantity from input field
   */
  setQuantity(event: any): void {
    const value = parseInt(event.target.value);
    this.productQuantity = (!isNaN(value) && value > 0) ? value : 1;
    if (this.productQuantity < 1) {
      this.productQuantity = 1;
      event.target.value = '1';
    }
  }

  /**
   * Confirm product selection and assign to slot
   */
  confirmProductSelection(): void {
    if (!this.selectedProduct || !this.selectedSlot) return;

    this.selectedSlot.product = this.selectedProduct;
    this.selectedSlot.units = this.productQuantity;
    this.selectedSlot.price = this.selectedProduct.price;

    this.closeProductSelector();
  }

  /**
   * Remove product from slot
   */
  removeProductFromSlot(slot: Slot, event: Event): void {
    event.stopPropagation();
    slot.product = null;
    slot.units = 0;
    slot.price = 'N/A';
  }

  /**
   * Save all changes to backend
   */
  saveChanges(): void {
    if (!this.machine.machine_id) {
      console.error('Cannot save: No machine ID available');
      this.errorMessage = 'Cannot save: No machine selected.';
      return;
    }

    const vendingState = this.vendingRows.map(row => ({
      rowId: row.id,
      slots: row.slots.map(slot => ({
        name: slot.name,
        enabled: slot.enabled,
        productId: slot.product ? slot.product.product_id : null,
        units: slot.units,
        price: slot.price
      }))
    }));

    this.isLoading = true;
    this.machineService.updateMachineVendingState(this.machine.machine_id, vendingState)
      .subscribe({
        next: (response) => {
          console.log('Vending state updated:', response);
          alert('Machine configuration saved successfully!');
          this.errorMessage = null;
          this.isLoading = false;
        },
        error: (error) => {
          console.error('Error updating vending state:', error);
          this.errorMessage = 'Failed to save machine configuration. Please try again.';
          this.isLoading = false;
        }
      });
  }

  /**
   * Navigate back to machines list
   */
  goBack(): void {
    this.router.navigate(['/machines/machines-list']);
  }
}