// sales.component.ts
import { Component, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { MatPaginatorModule, PageEvent } from '@angular/material/paginator';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { environment } from '../../../../../../environments/environment';

interface Transaction {
  id: number;
  transaction_id: string;
  machine_id: string;
  product_name: string;
  quantity: number;
  amount: number;
  payment_type: string;
  status: string;
  amount_receiving_status: string | null;
  return_amount: number | null;
  created_at: string;
}

@Component({
  selector: 'app-sales',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    MatDialogModule,
    MatButtonModule,
    MatIconModule,
    MatFormFieldModule,
    MatInputModule,
    MatSelectModule,
    MatPaginatorModule,
    MatProgressBarModule,
    MatProgressSpinnerModule
  ],
  templateUrl: './sales.component.html',
  styleUrls: ['./sales.component.scss']
})
export class SalesComponent implements OnInit {
  @ViewChild('detailsDialog') detailsDialog!: TemplateRef<any>;

  transactions: Transaction[] = [];
  filteredTransactions: Transaction[] = [];
  loading = false;
  error: string | null = null;
  
  private apiUrl = environment.apiUrl;
  
  filters = {
    machineId: '',
    transactionId: '',
    productName: '',
    status: ''
  };
  
  currentPage = 1;
  itemsPerPage = 10;
  
  selectedTransaction: Transaction | null = null;

  constructor(
    private http: HttpClient,
    private dialog: MatDialog
  ) {}

  ngOnInit() {
    this.loadTransactions();
  }

  private getHeaders(): HttpHeaders {
    const token = localStorage.getItem('accessToken');
    return new HttpHeaders().set('Authorization', `Bearer ${token}`);
  }

  loadTransactions() {
    this.loading = true;
    this.error = null;
    
    this.http.get<Transaction[]>(`${this.apiUrl}/transactions`, { 
      headers: this.getHeaders() 
    }).subscribe({
      next: (data) => {
        this.transactions = data;
        this.applyFilters();
        this.loading = false;
      },
      error: (err) => {
        this.error = 'Failed to load transactions';
        console.error('Transaction loading error:', err);
        this.loading = false;
      }
    });
  }

  applyFilters() {
    this.filteredTransactions = this.transactions.filter(t => {
      const matchMachine = !this.filters.machineId || 
        t.machine_id.toLowerCase().includes(this.filters.machineId.toLowerCase());
      
      const matchTransaction = !this.filters.transactionId || 
        t.transaction_id.toLowerCase().includes(this.filters.transactionId.toLowerCase());
      
      const matchProduct = !this.filters.productName || 
        t.product_name.toLowerCase().includes(this.filters.productName.toLowerCase());
      
      const matchStatus = !this.filters.status || t.status === this.filters.status;
      
      return matchMachine && matchTransaction && matchProduct && matchStatus;
    });
    
    this.currentPage = 1;
  }

  clearFilters() {
    this.filters = {
      machineId: '',
      transactionId: '',
      productName: '',
      status: ''
    };
    this.applyFilters();
  }

  get paginatedTransactions() {
    const start = (this.currentPage - 1) * this.itemsPerPage;
    const end = start + this.itemsPerPage;
    return this.filteredTransactions.slice(start, end);
  }

  onPageChange(event: PageEvent) {
    this.currentPage = event.pageIndex + 1;
    this.itemsPerPage = event.pageSize;
  }

  viewDetails(transaction: Transaction) {
    this.selectedTransaction = transaction;
    this.dialog.open(this.detailsDialog, {
      width: '600px',
      maxHeight: '90vh'
    });
  }

  processRefund(transaction: Transaction) {
    if (!confirm(`Process refund of ₹${transaction.amount.toFixed(2)} for transaction ${transaction.transaction_id}?`)) {
      return;
    }
    
    this.http.post(
      `${this.apiUrl}/transactions/${transaction.transaction_id}/refund`, 
      {}, 
      { headers: this.getHeaders() }
    ).subscribe({
      next: () => {
        alert('Refund processed successfully');
        this.loadTransactions();
        this.dialog.closeAll();
      },
      error: (err) => {
        alert('Failed to process refund: ' + (err.error?.error || 'Unknown error'));
        console.error('Refund error:', err);
      }
    });
  }

  getStatusClass(status: string): string {
    switch (status) {
      case 'Success': return 'success';
      case 'Dispense failed': return 'failed';
      case 'Unprocessed': return 'unprocessed';
      default: return '';
    }
  }

  exportToCSV() {
    const headers = ['ID', 'Machine ID', 'Transaction ID', 'Product Name', 'Quantity', 
                     'Status', 'Amount', 'Payment Type', 'Date & Time'];
    
    const rows = this.filteredTransactions.map(t => [
      t.id,
      t.machine_id,
      t.transaction_id,
      t.product_name,
      t.quantity,
      t.status,
      t.amount,
      t.payment_type,
      t.created_at
    ]);
    
    const csvContent = [
      headers.join(','),
      ...rows.map(row => row.join(','))
    ].join('\n');
    
    const blob = new Blob([csvContent], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `transactions_${new Date().toISOString().split('T')[0]}.csv`;
    link.click();
  }

  trackByFn(index: number, item: Transaction): number {
    return item.id;
  }
}