import { Component, OnInit, OnDestroy, ViewChild } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormControl } from '@angular/forms';
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 { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { BehaviorSubject, Observable, Subject, debounceTime, distinctUntilChanged, map, takeUntil } from 'rxjs';
import { SubCategoryService, SubCategory } from './subcategory.service';
import { CategoryService, Category } from '../categories/category.service';
import { BrandService, Brand } from '../brand/brand.service';
import { BranchService, Branch } from '../../company/branch-list/branch.service';

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

  subCategories$: Observable<SubCategory[]>;
  private subCategoriesSubject = new BehaviorSubject<SubCategory[]>([]);
  private destroy$ = new Subject<void>();

  searchInputControl = new FormControl('');
  selectedSubCategoryForm!: FormGroup;
  selectedSubCategory: SubCategory | null = null;
  isLoading = false;
  flashMessage: 'success' | 'error' | null = null;

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

  // All data
  branches: Branch[] = [];
  brands: Brand[] = [];
  categories: Category[] = [];

  // Filtered data for cascading
  filteredBrands: Brand[] = [];
  filteredCategories: Category[] = [];

  // Auto-fill values
  selectedBranchId = '';
  selectedBranchName = '';
  selectedBrandId = '';
  selectedCategoryId = '';
  selectedCategoryName = '';
  previewSubCategoryId = 'XXX0001';

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

  constructor(
    private fb: FormBuilder,
    private subCategoryService: SubCategoryService,
    private categoryService: CategoryService,
    private brandService: BrandService,
    private branchService: BranchService,
    private snackBar: MatSnackBar
  ) {
    this.subCategories$ = this.subCategoriesSubject.asObservable();
    this.initializeForm();
  }

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

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

  private initializeForm(): void {
    this.selectedSubCategoryForm = this.fb.group({
      name: ['', [Validators.required, Validators.minLength(2)]],
      branch_id: ['', [Validators.required]],
      brand_id: ['', [Validators.required]],
      category_id: ['', [Validators.required]]
    });
  }

  private setupSearch(): void {
    this.searchInputControl.valueChanges.pipe(
      debounceTime(300),
      distinctUntilChanged(),
      takeUntil(this.destroy$)
    ).subscribe((searchTerm) => {
      this.filterSubCategories(searchTerm || '');
    });
  }

  loadBranches(): void {
    this.branchService.getAllBranches().pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (branches) => { this.branches = branches; },
        error: (error) => this.showSnackBar('Failed to load branches', 'error')
      });
  }

  loadBrands(): void {
    this.brandService.getAllBrands().pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (brands) => { this.brands = brands; },
        error: (error) => this.showSnackBar('Failed to load brands', 'error')
      });
  }

  loadCategories(): void {
    this.categoryService.getAllCategories().pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (categories) => { this.categories = categories; },
        error: (error) => this.showSnackBar('Failed to load categories', 'error')
      });
  }

  loadSubCategories(): void {
    this.isLoading = true;
    this.subCategoryService.getAllSubCategories().pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (subCategories) => {
          this.subCategoriesSubject.next(subCategories);
          this.pagination.length = subCategories.length;
          this.isLoading = false;
        },
        error: (error) => {
          this.showSnackBar('Failed to load sub-categories', 'error');
          this.isLoading = false;
        }
      });
  }

  private filterSubCategories(searchTerm: string): void {
    this.subCategoryService.getAllSubCategories().pipe(
      map(subCategories => {
        if (!searchTerm) return subCategories;
        const term = searchTerm.toLowerCase();
        return subCategories.filter(sub =>
          sub.name.toLowerCase().includes(term) ||
          sub.sub_category_id.toLowerCase().includes(term) ||
          sub.category_name.toLowerCase().includes(term) ||
          sub.brand_name.toLowerCase().includes(term)
        );
      }),
      takeUntil(this.destroy$)
    ).subscribe(filtered => {
      this.subCategoriesSubject.next(filtered);
      this.pagination.length = filtered.length;
    });
  }

  onNameChange(event: any): void {
    const name = event.target.value;
    this.previewSubCategoryId = name ? this.generateSubCategoryIdPreview(name) : 'XXX0001';
  }

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

  // Level 1: Branch Selection
  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;
      
      // Filter brands by branch
      this.filteredBrands = this.brands.filter(b => b.branch_id === branchId);
      
      // Reset downstream selections
      this.selectedSubCategoryForm.patchValue({ brand_id: '', category_id: '' });
      this.selectedBrandId = '';
      this.selectedCategoryId = '';
      this.selectedCategoryName = '';
      this.filteredCategories = [];
    }
  }

  // Level 2: Brand Selection
  onBrandChange(event: any): void {
    const brandId = event.value;
    const brand = this.brands.find(b => b.brand_id === brandId);
    
    if (brand) {
      this.selectedBrandId = brand.brand_id;
      
      // Filter categories by brand
      this.filteredCategories = this.categories.filter(c => c.brand_id === brandId);
      
      // Reset downstream selections
      this.selectedSubCategoryForm.patchValue({ category_id: '' });
      this.selectedCategoryId = '';
      this.selectedCategoryName = '';
    }
  }

  // Level 3: Category Selection
  onCategoryChange(event: any): void {
    const categoryId = event.value;
    const category = this.categories.find(c => c.category_id === categoryId);
    
    if (category) {
      this.selectedCategoryId = category.category_id;
      this.selectedCategoryName = category.name;
    }
  }

  onImageSelected(event: any): void {
    const file = event.target.files[0];
    if (file) {
      if (file.size > 5 * 1024 * 1024) {
        this.showSnackBar('Image size must be less than 5MB', 'error');
        return;
      }
      if (!file.type.startsWith('image/')) {
        this.showSnackBar('Please select an image file', 'error');
        return;
      }
      this.selectedImageFile = file;
      const reader = new FileReader();
      reader.onload = (e: any) => { this.imagePreview = e.target.result; };
      reader.readAsDataURL(file);
    }
  }

  removeImage(): void {
    this.imagePreview = null;
    this.selectedImageFile = null;
    if (this.selectedSubCategory?.id) this.selectedSubCategory.image = null;
  }

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

  createSubCategory(): void {
    this.selectedSubCategory = {
      id: 0, sub_category_id: '', name: '', image: null,
      category_id: '', category_name: '', brand_id: '', brand_name: '',
      branch_id: '', branch_name: '', created_at: '', updated_at: ''
    };
    this.selectedSubCategoryForm.reset();
    this.selectedBranchId = '';
    this.selectedBranchName = '';
    this.selectedBrandId = '';
    this.selectedCategoryId = '';
    this.selectedCategoryName = '';
    this.filteredBrands = [];
    this.filteredCategories = [];
    this.previewSubCategoryId = 'XXX0001';
    this.imagePreview = null;
    this.selectedImageFile = null;
    this.flashMessage = null;
  }

  editSubCategory(subCategory: SubCategory): void {
    this.selectedSubCategory = { ...subCategory };
    this.selectedSubCategoryForm.patchValue({
      name: subCategory.name,
      branch_id: subCategory.branch_id,
      brand_id: subCategory.brand_id,
      category_id: subCategory.category_id
    });
    this.selectedBranchId = subCategory.branch_id;
    this.selectedBranchName = subCategory.branch_name;
    this.selectedBrandId = subCategory.brand_id;
    this.selectedCategoryId = subCategory.category_id;
    this.selectedCategoryName = subCategory.category_name;
    this.filteredBrands = this.brands.filter(b => b.branch_id === subCategory.branch_id);
    this.filteredCategories = this.categories.filter(c => c.brand_id === subCategory.brand_id);
    this.previewSubCategoryId = subCategory.sub_category_id;
    this.imagePreview = subCategory.image ? this.getFullImageUrl(subCategory.image) : null;
    this.selectedImageFile = null;
    this.flashMessage = null;
  }

  toggleDetails(subCategoryId: number): void {
    if (this.selectedSubCategory?.id === subCategoryId) {
      this.closeDetails();
    } else {
      const subCategory = this.subCategoriesSubject.value.find(s => s.id === subCategoryId);
      if (subCategory) this.editSubCategory(subCategory);
    }
  }

  closeDetails(): void {
    this.selectedSubCategory = null;
    this.selectedSubCategoryForm.reset();
    this.selectedBranchId = '';
    this.selectedBranchName = '';
    this.selectedBrandId = '';
    this.selectedCategoryId = '';
    this.selectedCategoryName = '';
    this.filteredBrands = [];
    this.filteredCategories = [];
    this.previewSubCategoryId = 'XXX0001';
    this.imagePreview = null;
    this.selectedImageFile = null;
    this.flashMessage = null;
  }

  updateSelectedSubCategory(): void {
    if (this.selectedSubCategoryForm.invalid) {
      this.selectedSubCategoryForm.markAllAsTouched();
      return;
    }
    this.isLoading = true;
    const formData = new FormData();
    formData.append('name', this.selectedSubCategoryForm.get('name')?.value);
    formData.append('branch_id', this.selectedSubCategoryForm.get('branch_id')?.value);
    formData.append('brand_id', this.selectedSubCategoryForm.get('brand_id')?.value);
    formData.append('category_id', this.selectedSubCategoryForm.get('category_id')?.value);
    if (this.selectedImageFile) formData.append('image', this.selectedImageFile);

    const operation = this.selectedSubCategory?.id
      ? this.subCategoryService.updateSubCategory(this.selectedSubCategory.id, formData)
      : this.subCategoryService.createSubCategory(formData);

    operation.pipe(takeUntil(this.destroy$)).subscribe({
      next: (subCategory) => {
        this.flashMessage = 'success';
        this.isLoading = false;
        this.showSnackBar(
          this.selectedSubCategory?.id ? 'SubCategory updated successfully' : 'SubCategory created successfully',
          'success'
        );
        setTimeout(() => {
          this.closeDetails();
          this.loadSubCategories();
        }, 1500);
      },
      error: (error) => {
        this.flashMessage = 'error';
        this.isLoading = false;
        this.showSnackBar(error.error?.error || 'Failed to save sub-category', 'error');
      }
    });
  }

  deleteSelectedSubCategory(): void {
    if (!this.selectedSubCategory?.id) return;
    if (!confirm(`Are you sure you want to delete sub-category "${this.selectedSubCategory.name}"?`)) return;
    this.deleteSubCategory(this.selectedSubCategory);
  }

  deleteSubCategory(subCategory: SubCategory): void {
    if (!confirm(`Are you sure you want to delete sub-category "${subCategory.name}"?`)) return;
    this.isLoading = true;
    this.subCategoryService.deleteSubCategory(subCategory.id).pipe(takeUntil(this.destroy$))
      .subscribe({
        next: () => {
          this.showSnackBar('SubCategory deleted successfully', 'success');
          this.closeDetails();
          this.loadSubCategories();
        },
        error: (error) => {
          this.showSnackBar(error.error?.error || 'Failed to delete sub-category', 'error');
          this.isLoading = false;
        }
      });
  }

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

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