import { Component, OnInit, ViewChild, Input } from '@angular/core';
import { Product, ProductService } from '../product.service';
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormControl } from '@angular/forms';
import { NgIf, NgFor, CurrencyPipe, CommonModule, DatePipe } from '@angular/common';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import { MatSortModule, MatSort } from '@angular/material/sort';
import { MatPaginatorModule, MatPaginator } from '@angular/material/paginator';
import { MatSelectModule } from '@angular/material/select';
import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatRippleModule } from '@angular/material/core';
import { MatTooltipModule } from '@angular/material/tooltip';
import { environment } from '@environments/environment'; 

@Component({
  selector: 'app-product-list',
  standalone: true,
  templateUrl: './product-list.component.html',
  styleUrls: ['./product-list.component.scss'],
  imports: [
    ReactiveFormsModule,
    CommonModule,
    CurrencyPipe,
    DatePipe,
    MatIconModule,
    MatButtonModule,
    MatSortModule,
    MatPaginatorModule,
    MatSelectModule,
    MatInputModule,
    MatFormFieldModule,
    MatProgressBarModule,
    MatRippleModule,
    MatTooltipModule
  ]
})
export class ProductListComponent implements OnInit {
  @Input() selectionMode: boolean = false;

  // Properties for inventory UI
  isLoading = false;
  products: Product[] = [];
  selectedProduct: Product | null = null;
  pagination = {
    length: 0,
    page: 0,
    size: 10
  };

  // Add product form properties (inline form instead of modal)
  showAddForm = false;
  isAddingProduct = false;
  addProductImagePreview: string | null = null;
  addProductForm: FormGroup;
  addProductSelectedFile: File | null = null;
  currentDate = new Date();

  // Flash message properties
  flashMessage: 'success' | 'error' | null = null;
  addFlashMessage: 'success' | 'error' | null = null;

  baseImageUrl = environment.apiUrl;
  categories: string[] = [];
  selectedCategory: string = 'All';
  searchControl = new FormControl('');

  selectedFile: File | null = null;
  productForm: FormGroup;

  private originalData: Product[] = [];

  @ViewChild(MatSort) sort!: MatSort;
  @ViewChild(MatPaginator) paginator!: MatPaginator;

  constructor(
    private productService: ProductService,
    private formBuilder: FormBuilder
  ) {
    // Existing product form for editing
    this.productForm = this.formBuilder.group({
      product_name: ['', Validators.required],
      price: ['', [Validators.required, Validators.min(0)]],
      created_date: [{ value: new Date(), disabled: true }],
      product_id: [{ value: null, disabled: true }],
      category: ['']
    });

    // New add product form (inline)
    this.addProductForm = this.formBuilder.group({
      product_name: ['', Validators.required],
      price: [0, [Validators.required, Validators.min(0.01)]],
      category: ['']
    });

    this.searchControl.valueChanges.subscribe(query => {
      this.onSearchChange(query || '');
    });
  }

  ngOnInit(): void {
    this.loadProducts();
  }

  loadProducts(): void {
    this.isLoading = true;
    this.productService.getProducts().subscribe(
      (data) => {
        const dataWithCategories = data.map(product => {
          if (!product.category) {
            if (product.product_name.toLowerCase().includes('lays') || 
                product.product_name.toLowerCase().includes('dorito')) {
              return { ...product, category: 'Snacks' };
            } else if (product.product_name.toLowerCase().includes('7up')) {
              return { ...product, category: 'Beverages' };
            } else {
              return { ...product, category: 'General' };
            }
          }
          return product;
        });

        this.originalData = dataWithCategories;
        this.products = [...this.originalData];
        this.categories = ['All', ...new Set(dataWithCategories.map(product => product.category).filter(category => category))];
        this.pagination.length = this.products.length;
        this.applyFilters();
        this.isLoading = false;
      },
      (error) => {
        console.error('Error fetching products:', error);
        this.isLoading = false;
      }
    );
  }

  applyFilters(): void {
    let filteredData = [...this.originalData];

    if (this.selectedCategory !== 'All') {
      filteredData = filteredData.filter(product => product.category === this.selectedCategory);
    }

    const query = this.searchControl.value?.trim().toLowerCase() || '';
    if (query) {
      filteredData = filteredData.filter(product =>
        product.product_name.toLowerCase().includes(query) ||
        product.product_id?.toString().includes(query)
      );
    }

    this.products = filteredData;
    this.pagination.length = filteredData.length;
  }

  onCategoryChange(category: string): void {
    this.selectedCategory = category;
    this.applyFilters();
  }

  onSearchChange(query: string): void {
    this.applyFilters();
  }

  trackByFn(index: number, product: Product): string {
    return product.product_id || index.toString();
  }

  getImageUrl(imageFileName: string | null): string {
    if (imageFileName) {
      return `${this.baseImageUrl}${imageFileName}`;
    }
    return '';
  }

  handleImageError(product: Product): void {
    product.product_image = null;
  }

  toggleDetails(productId: string): void {
    if (this.selectedProduct?.product_id === productId) {
      this.selectedProduct = null;
    } else {
      const prod = this.products.find(p => p.product_id === productId) || null;
      this.selectedProduct = prod;
      if (prod) {
        // Ensure we have the numeric id for updates
        console.log('Selected product for editing:', prod); // Debug log
        this.productForm.patchValue({
          product_name: prod.product_name,
          price: prod.price,
          created_date: prod.created_date,
          product_id: prod.product_id,
          category: prod.category
        });
      }
    }
  }

  // Inline Add Product Methods (replaces modal)
  toggleAddProduct(): void {
    if (this.showAddForm) {
      this.cancelAddProduct();
    } else {
      // Close any open product details
      this.selectedProduct = null;
      this.showAddForm = true;
      this.addProductForm.reset({
        product_name: '',
        price: 0,
        category: ''
      });
      this.addProductImagePreview = null;
      this.addProductSelectedFile = null;
      this.addFlashMessage = null;
    }
  }

  cancelAddProduct(): void {
    this.showAddForm = false;
    this.addProductForm.reset();
    this.addProductImagePreview = null;
    this.addProductSelectedFile = null;
    this.addFlashMessage = null;
  }

  onAddProductImageChange(event: any): void {
    const file = event.target.files[0];
    if (file) {
      this.addProductSelectedFile = file;
      const reader = new FileReader();
      reader.onload = (e) => {
        this.addProductImagePreview = e.target?.result as string;
      };
      reader.readAsDataURL(file);
    } else {
      this.addProductSelectedFile = null;
      this.addProductImagePreview = null;
    }
  }

  onAddProduct(): void {
    if (this.addProductForm.valid) {
      this.isAddingProduct = true;

      const formData = new FormData();
      formData.append('product_name', this.addProductForm.get('product_name')?.value);
      formData.append('price', this.addProductForm.get('price')?.value.toString());
      formData.append('created_date', new Date().toISOString());
      
      const category = this.addProductForm.get('category')?.value;
      if (category) {
        formData.append('category', category);
      }
      
      if (this.addProductSelectedFile) {
        formData.append('product_image', this.addProductSelectedFile);
      }

      this.productService.addProduct(formData).subscribe(
        (response) => {
          this.isAddingProduct = false;
          this.showAddFlashMessage('success');
          this.loadProducts();
          // Reset form but keep it open for potential additional entries
          this.addProductForm.reset({
            product_name: '',
            price: 0,
            category: ''
          });
          this.addProductImagePreview = null;
          this.addProductSelectedFile = null;
        },
        (error) => {
          this.isAddingProduct = false;
          this.showAddFlashMessage('error');
          console.error('Error adding product:', error);
        }
      );
    }
  }

  // Flash message helpers
  showFlashMessage(type: 'success' | 'error'): void {
    this.flashMessage = type;
    setTimeout(() => {
      this.flashMessage = null;
    }, 3000);
  }

  showAddFlashMessage(type: 'success' | 'error'): void {
    this.addFlashMessage = type;
    setTimeout(() => {
      this.addFlashMessage = null;
    }, 3000);
  }

  // Form submission handler
  submitForm(): void {
    if (this.productForm.valid && this.selectedProduct?.product_id) {
      this.updateProduct();
    }
  }

  updateProduct(): void {
    if (!this.selectedProduct?.id) {
      console.error('No product selected for update or missing numeric ID');
      console.log('Selected product:', this.selectedProduct); // Debug log
      this.showFlashMessage('error');
      return;
    }

    this.isLoading = true;
    const formData = new FormData();
    formData.append('product_name', this.productForm.get('product_name')?.value);
    formData.append('price', this.productForm.get('price')?.value.toString());
    
    let createdDate = this.productForm.get('created_date')?.value;
    if (createdDate && !(createdDate instanceof Date)) {
      createdDate = new Date(createdDate);
    }
    formData.append('created_date', createdDate.toISOString());
    
    const category = this.productForm.get('category')?.value;
    if (category) {
      formData.append('category', category);
    }
    
    if (this.selectedFile) {
      formData.append('product_image', this.selectedFile);
    }

    console.log('Updating product with numeric ID:', this.selectedProduct.id);

    this.productService.updateProduct(this.selectedProduct.id, formData).subscribe(
      (response) => {
        this.isLoading = false;
        this.showFlashMessage('success');
        this.loadProducts();
        this.selectedProduct = null;
        this.selectedFile = null;
      },
      (error) => {
        this.isLoading = false;
        this.showFlashMessage('error');
        console.error('Error updating product:', error);
      }
    );
  }

  deleteProduct(productId: string): void {
    // Find the product to get its numeric ID
    const product = this.products.find(p => p.product_id === productId);
    if (!product?.id) {
      console.error('Product not found or missing numeric ID:', productId);
      return;
    }

    if (confirm('Are you sure you want to delete this product?')) {
      this.productService.deleteProduct(product.id).subscribe(
        () => {
          this.products = this.products.filter(p => p.product_id !== productId);
          this.originalData = this.originalData.filter(p => p.product_id !== productId);
          this.pagination.length = this.products.length;
          if (this.selectedProduct?.product_id === productId) {
            this.selectedProduct = null;
          }
          this.showFlashMessage('success');
        },
        (error) => {
          this.showFlashMessage('error');
          console.error('Error deleting product:', error);
        }
      );
    }
  }

  onFileChange(event: any): void {
    if (event.target.files && event.target.files.length > 0) {
      this.selectedFile = event.target.files[0];
    } else {
      this.selectedFile = null;
    }
  }
}