import { Component, OnInit, OnDestroy, ViewChild } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormControl } from '@angular/forms';
import { MatTableModule } from '@angular/material/table';
import { MatPaginatorModule, MatPaginator } from '@angular/material/paginator';
import { MatSortModule, MatSort } from '@angular/material/sort';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatDialogModule } from '@angular/material/dialog';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { BehaviorSubject, Observable, Subject, debounceTime, distinctUntilChanged, map, switchMap, takeUntil } from 'rxjs';
import { BrandService, Brand } from './brand.service';
import { BranchService, Branch } from '../../company/branch-list/branch.service';

@Component({
  selector: 'app-brand',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    MatTableModule,
    MatPaginatorModule,
    MatSortModule,
    MatFormFieldModule,
    MatInputModule,
    MatSelectModule,
    MatButtonModule,
    MatIconModule,
    MatTooltipModule,
    MatProgressBarModule,
    MatDialogModule,
    MatSnackBarModule
  ],
  templateUrl: './brand.component.html',
  styleUrl: './brand.component.scss'
})
export class BrandComponent implements OnInit, OnDestroy {
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

  // Observables
  brands$: Observable<Brand[]>;
  private brandsSubject = new BehaviorSubject<Brand[]>([]);
  private destroy$ = new Subject<void>();

  // Form controls
  searchInputControl = new FormControl('');
  selectedBrandForm!: FormGroup;

  // State management
  selectedBrand: Brand | null = null;
  isLoading = false;
  flashMessage: 'success' | 'error' | null = null;

  // Pagination
  pagination = {
    length: 0,
    page: 0,
    size: 10
  };

  // Branches for dropdown
  branches: Branch[] = [];

  // Auto-fill fields
  selectedBranchId = '';
  selectedBranchName = '';
  previewBrandId = 'XXX0001';

  // Image handling
  imagePreview: string | null = null;
  selectedImageFile: File | null = null;

  constructor(
    private fb: FormBuilder,
    private brandService: BrandService,
    private branchService: BranchService,
    private snackBar: MatSnackBar
  ) {
    this.brands$ = this.brandsSubject.asObservable();
    this.initializeForm();
  }

  ngOnInit(): void {
    this.loadBranches();
    this.loadBrands();
    this.setupSearch();
  }

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }

  /**
   * Initialize the brand form
   */
  private initializeForm(): void {
    this.selectedBrandForm = this.fb.group({
      name: ['', [Validators.required, Validators.minLength(2)]],
      branch_id: ['', [Validators.required]]
    });
  }

  /**
   * Setup search functionality with debounce
   */
  private setupSearch(): void {
    this.searchInputControl.valueChanges
      .pipe(
        debounceTime(300),
        distinctUntilChanged(),
        takeUntil(this.destroy$)
      )
      .subscribe((searchTerm) => {
        this.filterBrands(searchTerm || '');
      });
  }

  /**
   * Load all branches for dropdown
   */
  loadBranches(): void {
    this.branchService.getAllBranches()
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (branches) => {
          this.branches = branches;
          console.log('Branches loaded:', branches.length);
        },
        error: (error) => {
          console.error('Error loading branches:', error);
          this.showSnackBar('Failed to load branches', 'error');
        }
      });
  }

  /**
   * Load all brands from the backend
   */
  loadBrands(): void {
    this.isLoading = true;
    
    this.brandService.getAllBrands()
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (brands) => {
          this.brandsSubject.next(brands);
          this.pagination.length = brands.length;
          this.isLoading = false;
        },
        error: (error) => {
          console.error('Error loading brands:', error);
          this.showSnackBar('Failed to load brands', 'error');
          this.isLoading = false;
        }
      });
  }

  /**
   * Filter brands based on search term
   */
  private filterBrands(searchTerm: string): void {
    this.brandService.getAllBrands()
      .pipe(
        map(brands => {
          if (!searchTerm) {
            return brands;
          }
          
          const term = searchTerm.toLowerCase();
          return brands.filter(brand =>
            brand.name.toLowerCase().includes(term) ||
            brand.brand_id.toLowerCase().includes(term) ||
            brand.branch_name.toLowerCase().includes(term)
          );
        }),
        takeUntil(this.destroy$)
      )
      .subscribe(filtered => {
        this.brandsSubject.next(filtered);
        this.pagination.length = filtered.length;
      });
  }

  /**
   * Preview brand ID generation based on name
   */
  onNameChange(event: any): void {
    const name = event.target.value;
    if (name) {
      this.previewBrandId = this.generateBrandIdPreview(name);
    } else {
      this.previewBrandId = 'XXX0001';
    }
  }

  /**
   * Generate brand ID preview (frontend simulation)
   */
  private generateBrandIdPreview(name: string): string {
    const lettersOnly = name.replace(/[^a-zA-Z]/g, '').toUpperCase();
    const prefix = lettersOnly.substring(0, 3).padEnd(3, 'X');
    return `${prefix}0001`;
  }

  /**
   * Handle branch selection change
   */
  onBranchChange(event: any): void {
    const branchId = event.value;
    const branch = this.branches.find(b => b.branch_id === branchId);
    
    if (branch) {
      this.selectedBranchId = branch.branch_id;
      this.selectedBranchName = branch.name;
    } else {
      this.selectedBranchId = '';
      this.selectedBranchName = '';
    }
  }

  /**
   * Handle image selection
   */
  onImageSelected(event: any): void {
    const file = event.target.files[0];
    if (file) {
      // Validate file size (5MB max)
      if (file.size > 5 * 1024 * 1024) {
        this.showSnackBar('Image size must be less than 5MB', 'error');
        return;
      }

      // Validate file type
      if (!file.type.startsWith('image/')) {
        this.showSnackBar('Please select an image file', 'error');
        return;
      }

      this.selectedImageFile = file;

      // Create preview
      const reader = new FileReader();
      reader.onload = (e: any) => {
        this.imagePreview = e.target.result;
      };
      reader.readAsDataURL(file);
    }
  }

  /**
   * Remove selected image
   */
  removeImage(): void {
    this.imagePreview = null;
    this.selectedImageFile = null;
    
    if (this.selectedBrand?.id) {
      this.selectedBrand.image = null;
    }
  }

  /**
   * Get full image URL
   */
  getFullImageUrl(imagePath: string | null): string {
    if (!imagePath) return '';
    if (imagePath.startsWith('http')) return imagePath;
    return `http://localhost:5000${imagePath}`;
  }

  /**
   * Create new brand - open form
   */
  createBrand(): void {
    this.selectedBrand = {
      id: 0,
      brand_id: '',
      name: '',
      branch_id: '',
      branch_name: '',
      image: null,
      created_at: '',
      updated_at: ''
    };
    
    this.selectedBrandForm.reset();
    this.selectedBranchId = '';
    this.selectedBranchName = '';
    this.previewBrandId = 'XXX0001';
    this.imagePreview = null;
    this.selectedImageFile = null;
    this.flashMessage = null;
  }

  /**
   * Edit existing brand
   */
  editBrand(brand: Brand): void {
    this.selectedBrand = { ...brand };
    this.selectedBrandForm.patchValue({
      name: brand.name,
      branch_id: brand.branch_id
    });
    
    this.selectedBranchId = brand.branch_id;
    this.selectedBranchName = brand.branch_name;
    this.previewBrandId = brand.brand_id;
    this.imagePreview = brand.image ? this.getFullImageUrl(brand.image) : null;
    this.selectedImageFile = null;
    this.flashMessage = null;
  }

  /**
   * Toggle brand details view
   */
  toggleDetails(brandId: number): void {
    if (this.selectedBrand?.id === brandId) {
      this.closeDetails();
    } else {
      const brand = this.brandsSubject.value.find(b => b.id === brandId);
      if (brand) {
        this.editBrand(brand);
      }
    }
  }

  /**
   * Close details panel
   */
  closeDetails(): void {
    this.selectedBrand = null;
    this.selectedBrandForm.reset();
    this.selectedBranchId = '';
    this.selectedBranchName = '';
    this.previewBrandId = 'XXX0001';
    this.imagePreview = null;
    this.selectedImageFile = null;
    this.flashMessage = null;
  }

  /**
   * Update or create brand
   */
  updateSelectedBrand(): void {
    if (this.selectedBrandForm.invalid) {
      this.selectedBrandForm.markAllAsTouched();
      return;
    }

    this.isLoading = true;

    // Prepare form data
    const formData = new FormData();
    formData.append('name', this.selectedBrandForm.get('name')?.value);
    formData.append('branch_id', this.selectedBrandForm.get('branch_id')?.value);

    // Add image if selected
    if (this.selectedImageFile) {
      formData.append('image', this.selectedImageFile);
    }

    const operation = this.selectedBrand?.id
      ? this.brandService.updateBrand(this.selectedBrand.id, formData)
      : this.brandService.createBrand(formData);

    operation
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (brand) => {
          this.flashMessage = 'success';
          this.isLoading = false;
          this.showSnackBar(
            this.selectedBrand?.id ? 'Brand updated successfully' : 'Brand created successfully',
            'success'
          );
          
          setTimeout(() => {
            this.closeDetails();
            this.loadBrands();
          }, 1500);
        },
        error: (error) => {
          console.error('Error saving brand:', error);
          this.flashMessage = 'error';
          this.isLoading = false;
          this.showSnackBar(
            error.error?.error || 'Failed to save brand',
            'error'
          );
        }
      });
  }

  /**
   * Delete selected brand
   */
  deleteSelectedBrand(): void {
    if (!this.selectedBrand?.id) {
      return;
    }

    if (!confirm(`Are you sure you want to delete brand "${this.selectedBrand.name}"?`)) {
      return;
    }

    this.deleteBrand(this.selectedBrand);
  }

  /**
   * Delete brand
   */
  deleteBrand(brand: Brand): void {
    if (!confirm(`Are you sure you want to delete brand "${brand.name}"?`)) {
      return;
    }

    this.isLoading = true;

    this.brandService.deleteBrand(brand.id)
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: () => {
          this.showSnackBar('Brand deleted successfully', 'success');
          this.closeDetails();
          this.loadBrands();
        },
        error: (error) => {
          console.error('Error deleting brand:', error);
          this.showSnackBar(
            error.error?.error || 'Failed to delete brand',
            'error'
          );
          this.isLoading = false;
        }
      });
  }

  /**
   * Track by function for ngFor
   */
  trackByFn(index: number, item: Brand): number {
    return item.id;
  }

  /**
   * Show snackbar notification
   */
  private showSnackBar(message: string, type: 'success' | 'error'): void {
    this.snackBar.open(message, 'Close', {
      duration: 3000,
      horizontalPosition: 'end',
      verticalPosition: 'top',
      panelClass: type === 'success' ? 'snackbar-success' : 'snackbar-error'
    });
  }
}