import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ReactiveFormsModule, FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
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 { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatPaginatorModule } from '@angular/material/paginator';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatRippleModule } from '@angular/material/core';
import { BehaviorSubject } from 'rxjs';
import { Router } from '@angular/router';
import { MachineService } from '../machine.service';
import { AuthService } from 'app/core/auth/auth.service';

@Component({
  selector: 'app-machines-list',
  standalone: true,
  templateUrl: './machines-list.component.html',
  styleUrls: ['./machines-list.component.scss'],
  imports: [
    CommonModule,
    ReactiveFormsModule,
    MatFormFieldModule,
    MatInputModule,
    MatSelectModule,
    MatButtonModule,
    MatIconModule,
    MatProgressBarModule,
    MatPaginatorModule,
    MatCheckboxModule,
    MatRippleModule
  ]
})
export class MachinesListComponent implements OnInit {
  machines$ = new BehaviorSubject<any[]>([]);
  selectedMachine: any = null;
  selectedMachineForm: FormGroup;
  users: any[] = [];
  isLoading = false;

  flashMessage: string | null = null;

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

  searchInputControl = new FormControl('');

  // Role-based properties
  isClient: boolean = false;
  isAdmin: boolean = false;
  currentUserId: number | null = null;

  constructor(
    private machineService: MachineService,
    private fb: FormBuilder,
    private router: Router,
    private authService: AuthService 
  ) {
    this.selectedMachineForm = this.fb.group({
      machine_model: ['', Validators.required],
      machine_type: ['', Validators.required],
      client_id: [''],
      branch_name: ['', Validators.required],
      operation_status: ['', Validators.required],
      connection_status: ['', Validators.required],
      password: ['']
    });
  }

  ngOnInit(): void {
    // Check user role
    this.isClient = this.authService.hasRole('Client');
    this.isAdmin = this.authService.hasAnyRole(['Management', 'SuperAdmin', 'Admin']);
    
    // Get user ID from JWT token
    const token = this.authService.accessToken;
    if (token) {
      try {
        const payload = JSON.parse(atob(token.split('.')[1]));
        this.currentUserId = payload.user_id || null;
        console.log('User ID from token:', this.currentUserId);
      } catch (e) {
        console.error('Error decoding token:', e);
        this.currentUserId = null;
      }
    }
    
    console.log('Current user role:', this.authService.userRole);
    console.log('Is Client:', this.isClient);
    console.log('Is Admin:', this.isAdmin);
    console.log('Current User ID:', this.currentUserId);
    
    // Only admins need client_id validation
    if (this.isAdmin) {
      this.selectedMachineForm.get('client_id')?.setValidators([Validators.required]);
    }
    
    this.loadMachines();
    
    // Only admins need to load users list
    if (this.isAdmin) {
      this.loadUsers();
    }
  }

  loadMachines(): void {
    this.isLoading = true;
    this.machineService.getMachines().subscribe({
      next: (data) => {
        // If client, filter to show only their machines
        let filteredData = data;
        if (this.isClient && this.currentUserId) {
          filteredData = data.filter(m => m.client_id === this.currentUserId);
          console.log(`Filtered ${filteredData.length} machines for client`);
        }
        
        this.machines$.next(filteredData);
        this.pagination.length = filteredData.length;
        this.isLoading = false;
      },
      error: (err) => {
        console.error('Error loading machines:', err);
        this.isLoading = false;
      }
    });
  }

  loadUsers(): void {
    this.machineService.getUsers().subscribe({
      next: (data) => (this.users = data),
      error: (err) => console.error('Error loading users', err)
    });
  }

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

  toggleDetails(id: number): void {
    // Clients cannot edit, so don't allow toggle
    if (this.isClient) {
      return;
    }
    
    if (this.selectedMachine?.id === id) {
      this.selectedMachine = null;
    } else {
      const machine = this.machines$.value.find((m) => m.id === id);
      this.selectedMachine = machine;
      this.selectedMachineForm.patchValue(machine);
      this.selectedMachineForm.get('password')?.reset();
    }
  }

  createMachine(): void {
    // Clients cannot create machines
    if (this.isClient) {
      alert('You do not have permission to create machines.');
      return;
    }
    
    console.log('createMachine called');
    
    const defaultValues: any = {
      machine_model: '',
      machine_type: '',
      branch_name: '',
      operation_status: 'active',
      connection_status: 'disconnected',
      password: '',
      client_id: ''
    };
    
    this.selectedMachine = { 
      id: null,
      ...defaultValues,
      showPassword: false
    };
    
    this.selectedMachineForm.reset(defaultValues);
    
    console.log('New machine form values:', this.selectedMachineForm.value);
  }

  updateSelectedMachine(): void {
    // Clients cannot update machines
    if (this.isClient) {
      alert('You do not have permission to edit machines.');
      return;
    }
    
    if (!this.selectedMachineForm.valid) {
      console.log('Form invalid:', this.selectedMachineForm.errors);
      Object.keys(this.selectedMachineForm.controls).forEach(key => {
        const control = this.selectedMachineForm.get(key);
        if (control?.invalid) {
          console.log(`${key} is invalid:`, control.errors);
        }
      });
      return;
    }

    let payload = {
      ...this.selectedMachine,
      ...this.selectedMachineForm.value
    };

    console.log('Submitting machine payload:', payload);

    // Remove password when editing
    if (this.selectedMachine?.id) {
      delete payload.password;
    }

    if (this.selectedMachine?.id) {
      // Update existing machine
      this.machineService.updateMachine(this.selectedMachine.id, payload).subscribe({
        next: (updated) => {
          this.flashMessage = 'success';
          const machines = this.machines$.value.map((m) =>
            m.id === updated.id ? updated : m
          );
          this.machines$.next(machines);
          this.loadMachines();
        },
        error: (err) => {
          console.error('Update error:', err);
          this.flashMessage = 'error';
        }
      });
    } else {
      // Create new machine
      if (!payload.password) {
        this.flashMessage = 'error';
        alert('Password is required for new machine');
        return;
      }

      this.machineService.addMachine(payload).subscribe({
        next: (created) => {
          console.log('Machine created:', created);
          this.flashMessage = 'success';
          this.machines$.next([...this.machines$.value, created]);
          this.selectedMachine = null;
          this.loadMachines();
        },
        error: (err) => {
          console.error('Create error:', err);
          this.flashMessage = 'error';
        }
      });
    }

    setTimeout(() => (this.flashMessage = null), 3000);
  }

  deleteSelectedMachine(): void {
    // Clients cannot delete machines
    if (this.isClient) {
      alert('You do not have permission to delete machines.');
      return;
    }
    
    if (!this.selectedMachine?.id) return;

    if (!confirm('Are you sure you want to delete this machine?')) {
      return;
    }

    this.machineService.deleteMachine(this.selectedMachine.id).subscribe({
      next: () => {
        this.flashMessage = 'success';
        const machines = this.machines$.value.filter(
          (m) => m.id !== this.selectedMachine.id
        );
        this.machines$.next(machines);
        this.selectedMachine = null;
        this.loadMachines();
      },
      error: () => {
        this.flashMessage = 'error';
      }
    });

    setTimeout(() => (this.flashMessage = null), 3000);
  }

  viewMachineDetails(id: number): void {
    this.router.navigate(['/machines/machine-details', id]);
  }
}