// src/app/machine-slots/machine-slots.component.ts
import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { environment } from '../../environments/environment';
import { AuthService } from '../services/auth.service';

interface Slot {
  slot_name: string;  // row_id (A-F)
  column: number;
  enabled: boolean;
  product_id: string | null;
  units: number;
  price: string;
  product_name: string;
  product_image: string | null;
}

interface CartItem {
  slotId: string;
  productId: string;
  productName: string;
  productImage: string | null;
  quantity: number;
  price: number;
  totalPrice: number;
}

interface PaymentDialogData {
  cart: CartItem[];
  totalAmount: number;
  machineId: string;
}

@Component({
  selector: 'app-machine-slots',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './machine-slots.component.html',
  styleUrls: ['./machine-slots.component.scss']
})
export class MachineSlotsComponent implements OnInit {
  machineId: string | null = null;
  slots: Slot[] = [];
  loading = false;
  error = '';
  cartOpen = false;
  cart: CartItem[] = [];
  selectedQuantities: { [key: string]: number } = {};
  totalCartPrice = 0;
  
  // Payment dialog properties
  showPaymentDialog = false;
  paymentDialogData: PaymentDialogData | null = null;
  processingTransaction = false;

  constructor(
    private route: ActivatedRoute,
    private http: HttpClient,
    private authService: AuthService,
    private router: Router
  ) { }

  ngOnInit(): void {
    this.machineId = this.route.snapshot.paramMap.get('id') || this.authService.getLoggedInMachineId();
    console.log('Using machineId:', this.machineId);

    if (this.machineId) {
      this.loadMachineSlots();
    } else {
      this.error = 'Machine ID not found';
    }
  }

  loadMachineSlots() {
    this.loading = true;
    this.http.get<Slot[]>(`${environment.apiUrl}/machine-slots/${this.machineId}`).subscribe(
      (data) => {
        this.slots = data;
        this.slots.forEach(slot => {
          if (slot.product_id) {
            this.selectedQuantities[`${slot.slot_name}${slot.column}`] = 1;
          }
        });
        this.loading = false;
      },
      (error) => {
        this.error = 'Failed to load machine slots';
        this.loading = false;
      }
    );
  }

  getSlot(row: string, column: number): Slot | undefined {
    return this.slots.find(s => s.slot_name === row && s.column === column);
  }

  logout() {
    this.authService.logout();
    this.router.navigate(['/login']);
  }

  toggleCart() {
    this.cartOpen = !this.cartOpen;
  }

  addToCart(slot: Slot, slotId: string) {
    if (!slot.enabled || !slot.product_id || slot.units <= 0) return;

    const quantity = this.selectedQuantities[slotId];
    if (!quantity || quantity <= 0 || quantity > slot.units) return;

    const existingItemIndex = this.cart.findIndex(item => item.slotId === slotId);

    if (existingItemIndex !== -1) {
      this.cart[existingItemIndex].quantity = quantity;
      this.cart[existingItemIndex].totalPrice = quantity * parseFloat(slot.price);
    } else {
      this.cart.push({
        slotId,
        productId: slot.product_id,
        productName: slot.product_name,
        productImage: slot.product_image,
        quantity,
        price: parseFloat(slot.price),
        totalPrice: quantity * parseFloat(slot.price)
      });
    }

    this.calculateTotalCartPrice();
    this.debugCart();
  }

  removeFromCart(index: number) {
    this.cart.splice(index, 1);
    this.calculateTotalCartPrice();
  }

  updateCartItemQuantity(item: CartItem, quantity: number) {
    if (quantity > 0) {
      const slot = this.slots.find(s => s.slot_name + s.column === item.slotId);
      if (slot && quantity <= slot.units) {
        item.quantity = quantity;
        item.totalPrice = quantity * item.price;
        this.calculateTotalCartPrice();
      }
    }
  }

  calculateTotalCartPrice() {
    this.totalCartPrice = this.cart.reduce((total, item) => total + item.totalPrice, 0);
  }

  incrementQuantity(row: string, col: number): void {
    const slot = this.getSlot(row, col);
    if (!slot || !slot.units) return;
    
    const key = `${row}${col}`;
    const currentQuantity = this.selectedQuantities[key] || 1;
    
    if (currentQuantity < slot.units) {
      this.selectedQuantities[key] = currentQuantity + 1;
    }
  }

  decrementQuantity(row: string, col: number): void {
    const key = `${row}${col}`;
    const currentQuantity = this.selectedQuantities[key] || 1;
    
    if (currentQuantity > 1) {
      this.selectedQuantities[key] = currentQuantity - 1;
    }
  }

  // Simple payment dialog approach
  proceedToPayment() {
  console.log('=== PROCEED TO PAYMENT CLICKED ===');
  console.log('Machine ID:', this.machineId);
  console.log('Cart:', this.cart);
  console.log('Cart length:', this.cart.length);
  
  if (!this.machineId || this.cart.length === 0) {
    console.log('BLOCKED: Missing machine ID or empty cart');
    return;
  }

  console.log('Opening payment dialog...');
  this.paymentDialogData = {
    cart: [...this.cart],
    totalAmount: this.totalCartPrice,
    machineId: this.machineId
  };
  
  console.log('Payment dialog data:', this.paymentDialogData);
  this.showPaymentDialog = true;
  console.log('showPaymentDialog set to:', this.showPaymentDialog);
}

  closePaymentDialog() {
    this.showPaymentDialog = false;
    this.paymentDialogData = null;
  }

  handlePaymentPaid() {
  if (!this.paymentDialogData || this.processingTransaction) return;

  this.processingTransaction = true;

  // Prepare inventory update data
  const inventoryUpdates = this.paymentDialogData.cart.map(item => ({
    slotId: item.slotId,
    quantityDispensed: item.quantity
  }));

  const updateData = {
    machineId: this.machineId,
    inventoryUpdates: inventoryUpdates
  };

  // STEP 1: Update inventory FIRST
  this.http.post(`${environment.apiUrl}/machine-slots/update-inventory`, updateData).subscribe({
    next: (inventoryResponse: any) => {
      console.log('✓ Server inventory updated successfully:', inventoryResponse);
      
      // STEP 2: Now create transactions (only if inventory update succeeded)
      const transactionData = this.paymentDialogData!.cart.map(item => ({
        machine_id: this.paymentDialogData!.machineId,
        product_name: item.productName,
        quantity: item.quantity,
        amount: item.totalPrice,
        payment_type: 'cash',
        status: 'Success'
      }));

      this.http.post(`${environment.apiUrl}/transactions/bulk-create`, {
        transactions: transactionData
      }).subscribe({
        next: (transactionResponse: any) => {
          console.log('✓ Transactions created successfully:', transactionResponse);
          
          // STEP 3: Update local inventory
          this.updateLocalInventory(this.paymentDialogData!.cart);
          
          // STEP 4: Clear cart and close dialog
          this.clearCart();
          this.closePaymentDialog();
          
          // STEP 5: Show success message
          alert('Payment successful! Items dispensed.');
          
          // STEP 6: Reload slots to sync with server
          this.loadMachineSlots();
          
          this.processingTransaction = false;
        },
        error: (transactionError) => {
          console.error('✗ Error creating transactions:', transactionError);
          this.error = 'Inventory updated but transaction recording failed';
          this.processingTransaction = false;
          
          // Still reload to show updated inventory
          this.loadMachineSlots();
        }
      });
    },
    error: (inventoryError) => {
      console.error('✗ Failed to update server inventory:', inventoryError);
      this.error = 'Failed to update inventory. Payment not processed.';
      this.processingTransaction = false;
      
      // Don't create transactions if inventory update failed
      // This prevents selling items that couldn't be deducted from inventory
    }
  });
}

  handlePaymentCancel() {
    this.closePaymentDialog();
  }

  private updateLocalInventory(paidCart: CartItem[]) {
    paidCart.forEach(cartItem => {
      const slot = this.slots.find(s => 
        s.slot_name + s.column === cartItem.slotId
      );
      
      if (slot && slot.units >= cartItem.quantity) {
        slot.units -= cartItem.quantity;
        
        if (slot.units <= 0) {
          slot.enabled = false;
        }
      }
    });

    // Update selectedQuantities
    this.slots.forEach(slot => {
      if (slot.product_id && slot.units > 0) {
        this.selectedQuantities[`${slot.slot_name}${slot.column}`] = 1;
      } else {
        delete this.selectedQuantities[`${slot.slot_name}${slot.column}`];
      }
    });
  }

  private showSuccessMessage(message: string) {
    alert(message);
  }

  clearCart() {
    this.cart = [];
    this.totalCartPrice = 0;
  }

  generateQuantityOptions(slot: Slot): number[] {
    const options: number[] = [];
    for (let i = 1; i <= slot.units; i++) options.push(i);
    return options;
  }

  getUnitStatusClass(units: number): string {
    if (units <= 0) return 'empty';
    if (units <= 3) return 'low-stock';
    return '';
  }

  get formattedTotalAmount(): string {
  return this.paymentDialogData?.totalAmount !== undefined
    ? this.paymentDialogData.totalAmount.toFixed(2)
    : '0.00';
}

debugCart() {
  console.log('Cart state:');
  console.log('- Length:', this.cart.length);
  console.log('- Items:', this.cart);
  console.log('- Total:', this.totalCartPrice);
  console.log('- Machine ID:', this.machineId);
}


  /* ========================================
     PAYU PAYMENT GATEWAY CODE (HIDDEN FOR NOW)
     ========================================
     
  // Uncomment this section when you want to use PayU payment gateway
  
  interface PayUResponse {
    key: string;
    txnid: string;
    amount: string;
    productinfo: string;
    firstname: string;
    email: string;
    phone: string;
    surl: string;
    furl: string;
    hash: string;
    service_provider?: string;
    udf1?: string;
    udf2?: string;
    udf3?: string;
    udf4?: string;
    udf5?: string;
  }

  showingPaymentMessage = false;
  paymentSuccessMessage = false;
  paymentFailureMessage = false;

  proceedToPaymentWithPayU() {
    if (!this.machineId || this.cart.length === 0 || this.processingTransaction) return;

    this.processingTransaction = true;
    this.error = '';

    const dispensingInstructions = this.cart.map(item => ({
      slotId: item.slotId,
      rowId: item.slotId[0],
      column: parseInt(item.slotId.substring(1)),
      quantity: item.quantity
    }));

    const orderData = {
      machineId: this.machineId,
      dispensingInstructions,
      totalAmount: this.totalCartPrice.toFixed(2),
      productInfo: this.cart.map(item => `${item.productName} x ${item.quantity}`).join(', '),
      cartData: JSON.stringify(this.cart),
      userDetails: {
        firstname: 'Customer',
        email: 'customer@example.com',
        phone: '1234567890'
      }
    };

    if (typeof window !== 'undefined') {
      sessionStorage.setItem('pendingCart', JSON.stringify(this.cart));
      sessionStorage.setItem('pendingMachineId', this.machineId);
    }

    const headers = {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    };

    this.http.post<PayUResponse>(`${environment.apiUrl}/create-payu-order`, orderData, { headers }).subscribe({
      next: (payuData) => {
        if (!payuData || !payuData.key || !payuData.hash || !payuData.amount) {
          this.error = 'Invalid payment data received. Please try again.';
          this.processingTransaction = false;
          return;
        }
        this.redirectToPayU(payuData);
      },
      error: (error) => {
        if (error.status === 0) {
          this.error = 'Unable to connect to payment service. Please check your connection.';
        } else if (error.status === 404) {
          this.error = 'Payment service not found. Please contact support.';
        } else if (error.status >= 500) {
          this.error = 'Payment service is temporarily unavailable. Please try again.';
        } else {
          this.error = error.error?.error || 'There was a problem creating the payment order. Please try again.';
        }
        this.processingTransaction = false;
      }
    });
  }

  private redirectToPayU(payuData: PayUResponse) {
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = environment.payuUrl || 'https://test.payu.in/_payment';
    form.target = '_blank';
    form.style.display = 'none';

    const fields = [
      { name: 'key', value: payuData.key || '' },
      { name: 'txnid', value: payuData.txnid || '' },
      { name: 'amount', value: payuData.amount || '' },
      { name: 'productinfo', value: payuData.productinfo || '' },
      { name: 'firstname', value: payuData.firstname || '' },
      { name: 'email', value: payuData.email || '' },
      { name: 'phone', value: payuData.phone || '' },
      { name: 'surl', value: payuData.surl || '' },
      { name: 'furl', value: payuData.furl || '' },
      { name: 'hash', value: typeof payuData.hash === 'string' ? payuData.hash : String(payuData.hash) },
      { name: 'udf1', value: payuData.udf1 || this.machineId || '' },
      { name: 'udf2', value: payuData.udf2 || JSON.stringify(this.cart.map(item => ({
          slotId: item.slotId,
          quantity: item.quantity,
          productName: item.productName
        })))
      },
      { name: 'udf3', value: payuData.udf3 || '' },
      { name: 'udf4', value: payuData.udf4 || '' },
      { name: 'udf5', value: payuData.udf5 || '' }
    ];

    if (payuData.service_provider) {
      fields.push({ name: 'service_provider', value: payuData.service_provider });
    }

    fields.forEach(field => {
      const input = document.createElement('input');
      input.type = 'hidden';
      input.name = field.name;
      input.value = field.value;
      form.appendChild(input);
    });

    document.body.appendChild(form);
    form.submit();

    setTimeout(() => {
      if (document.body.contains(form)) {
        document.body.removeChild(form);
      }
      this.processingTransaction = false;
    }, 100);

    this.showPaymentTabMessage();
  }

  private showPaymentTabMessage() {
    this.showingPaymentMessage = true;
    setTimeout(() => {
      this.showingPaymentMessage = false;
    }, 10000);
  }

  private checkForPaymentSuccess() {
    if (typeof window === 'undefined') return;

    const urlParams = new URLSearchParams(window.location.search);
    const paymentStatus = urlParams.get('status');
    const txnid = urlParams.get('txnid');

    if (paymentStatus === 'success' && txnid) {
      this.handlePaymentSuccess();
      
      const url = new URL(window.location.href);
      url.searchParams.delete('status');
      url.searchParams.delete('txnid');
      url.searchParams.delete('amount');
      window.history.replaceState({}, document.title, url.toString());
    } else if (paymentStatus === 'failure') {
      this.showPaymentFailureMessage();
    }
  }

  handlePaymentSuccess() {
    if (typeof window !== 'undefined') {
      const pendingCart = sessionStorage.getItem('pendingCart');
      const pendingMachineId = sessionStorage.getItem('pendingMachineId');

      if (pendingCart && pendingMachineId && pendingMachineId === this.machineId) {
        try {
          const cartToProcess: CartItem[] = JSON.parse(pendingCart);
          this.processSuccessfulPayment(cartToProcess);
        } catch (e) {
          console.error('Error parsing pending cart for payment success:', e);
        }
      }
    }
  }

  private processSuccessfulPayment(paidCart: CartItem[]) {
    paidCart.forEach(cartItem => {
      const slot = this.slots.find(s => 
        s.slot_name + s.column === cartItem.slotId
      );
      
      if (slot && slot.units >= cartItem.quantity) {
        slot.units -= cartItem.quantity;
        if (slot.units <= 0) {
          slot.enabled = false;
        }
      }
    });

    this.clearCart();

    this.slots.forEach(slot => {
      if (slot.product_id && slot.units > 0) {
        this.selectedQuantities[`${slot.slot_name}${slot.column}`] = 1;
      } else {
        delete this.selectedQuantities[`${slot.slot_name}${slot.column}`];
      }
    });

    this.updateServerInventory(paidCart);

    if (typeof window !== 'undefined') {
      sessionStorage.removeItem('pendingCart');
      sessionStorage.removeItem('pendingMachineId');
    }

    this.showPaymentSuccessMessage();
  }

  private updateServerInventory(paidCart: CartItem[]) {
    const inventoryUpdates = paidCart.map(item => ({
      slotId: item.slotId,
      rowId: item.slotId[0],
      column: parseInt(item.slotId.substring(1)),
      quantityDispensed: item.quantity
    }));

    const updateData = {
      machineId: this.machineId,
      inventoryUpdates: inventoryUpdates
    };

    this.http.post(`${environment.apiUrl}/update-inventory`, updateData).subscribe({
      next: (response) => {
        console.log('Server inventory updated successfully:', response);
      },
      error: (error) => {
        console.error('Failed to update server inventory:', error);
        this.loadMachineSlots();
      }
    });
  }

  private showPaymentSuccessMessage() {
    this.paymentSuccessMessage = true;
    setTimeout(() => {
      this.paymentSuccessMessage = false;
    }, 5000);
  }

  private showPaymentFailureMessage() {
    this.paymentFailureMessage = true;
    setTimeout(() => {
      this.paymentFailureMessage = false;
    }, 8000);
  }

  restoreCartFromSession() {
    if (typeof window === 'undefined') return;

    const pendingCart = sessionStorage.getItem('pendingCart');
    const pendingMachineId = sessionStorage.getItem('pendingMachineId');

    if (pendingCart && pendingMachineId && pendingMachineId === this.machineId) {
      try {
        this.cart = JSON.parse(pendingCart);
        this.calculateTotalCartPrice();

        this.cart.forEach(item => {
          this.selectedQuantities[item.slotId] = item.quantity;
        });

        sessionStorage.removeItem('pendingCart');
        sessionStorage.removeItem('pendingMachineId');
      } catch (e) {
        console.error('Error parsing pending cart:', e);
      }
    }
  }

  ======================================== */
}