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 } from '../../products/product.service';
import { Subscription } from 'rxjs';

@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 = ['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 = [];
  filteredProducts = [];
  searchTerm = '';
  showProductSelector = false;
  selectedSlot = null;
  selectedRow = null;
  selectedProduct = null;
  productQuantity = 1;
  private subscriptions: Subscription[] = [];
  errorMessage: string | null = null; // To display error messages on the UI

  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());
  }

  loadMachineData(): void {
    // First, try to get the machine ID from the route
    const machineId = this.route.snapshot.paramMap.get('id');

    if (machineId) {
      this.machineService.getMachineById(Number(machineId)).subscribe(
        fetchedMachine => {
          if (fetchedMachine?.machine_id) {
            this.machine = fetchedMachine;
            this.machineService.setSelectedMachine(fetchedMachine);
            this.loadVendingState(fetchedMachine.machine_id);
            this.errorMessage = null; // Clear any previous error
          } else {
            console.warn('Could not find machine with ID:', machineId);
            this.errorMessage = 'Machine not found. Please select a machine from the list.';
            this.loadFallbackMachine();
          }
        },
        error => {
          console.error('Error fetching machine:', error);
          this.errorMessage = 'Error loading machine details. Please try again.';
          this.loadFallbackMachine();
        }
      );
    } else {
      // If no ID in route, try to load from selected machine
      this.loadFallbackMachine();
    }
  }

  private loadFallbackMachine(): void {
    const sub = this.machineService.selectedMachine$.subscribe(machine => {
      if (machine?.machine_id) {
        this.machine = machine;
        this.loadVendingState(machine.machine_id);
        // Update the URL with the machine ID to handle refresh
        this.router.navigate(['/machines', machine.id], {
          replaceUrl: true,
          skipLocationChange: false
        });
        this.errorMessage = null; // Clear any previous error
      } else {
        console.warn('No machine selected and no ID in route');
        this.errorMessage = 'No machine selected. Please select a machine from the list.';
        // Instead of navigating away, show an error message on the UI
      }
    });
    this.subscriptions.push(sub);
  }

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

  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;
              }
            }
          }
        });
      }
    });
  }

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

  toggleSlotStatus(row: any, slot: any, event: MouseEvent): void {
    event.stopPropagation();
    slot.enabled = !slot.enabled;
  }

  openProductSelector(row: any, slot: any, event: Event): void {
    if (!slot.enabled) return;

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

    this.filteredProducts.forEach(p => p.selected = false);

    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();
  }

  closeProductSelector(): void {
    this.showProductSelector = false;
    this.selectedRow = null;
    this.selectedSlot = null;
    this.selectedProduct = null;
    this.productQuantity = 1;
  }

  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;
    }
  }

  onProductSelectionChange(product: any): void {
    this.filteredProducts.forEach(p => p.selected = false);
    product.selected = true;
    this.selectedProduct = product;

    if (this.selectedSlot?.product?.product_id === product.product_id) {
      this.productQuantity = this.selectedSlot.units || 1;
    } else {
      this.productQuantity = 1;
    }
  }

  increaseQuantity(): void {
    this.productQuantity++;
  }

  decreaseQuantity(): void {
    // ✅ Allow decreasing quantity (minimum 1)
    if (this.productQuantity > 1) {
      this.productQuantity--;
    }
  }

  setQuantity(event: any): void {
    // ✅ Allow setting quantity always
    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';
    }
  }

  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();
  }

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

  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.machineService.updateMachineVendingState(this.machine.machine_id, vendingState)
      .subscribe(
        response => {
          console.log('Vending state updated:', response);
          alert('Machine configuration saved successfully!');
          this.errorMessage = null;
        },
        error => {
          console.error('Error updating vending state:', error);
          this.errorMessage = 'Failed to save machine configuration. Please try again.';
        }
      );
  }

  goBack() {
    this.router.navigate(['/machines/machines-list']);
  }
}