import { Component, OnInit } from '@angular/core';
import { UserTaskService } from '../user-task.service';
import { MatSnackBar } from '@angular/material/snack-bar';

@Component({
  selector: 'app-add-user-task',
  templateUrl: './add-user-task.component.html',
  styleUrls: ['./add-user-task.component.css']
})
export class AddUserTaskComponent implements OnInit {
  taskDetails: string = '';
  userCode: string = '';
  tokenId: string = 'ZXlKaGJHY2lPaUpJVXpJMU5pSjkuZXlKcWRHa2lPaUl3TURBd01EQXdOREV4SWl3aVlYQndiR2xqWVhScGIyNUpaQ0k2SWtaTVZWUlVSVkpCVUZBaUxDSnlaV2RwYjI0aU9pSWlMQ0prWlhOcFoyNWhkR2x2YmlJNklpSXNJbkpsY0c5eWRGUnZRMjlrWlNJNklpSXNJbTVoYldVaU9pSWdJaXdpWkdsMmFYTnBiMjRpT2lJaUxDSmxiV0ZwYkNJNklpSXNJbWh4SWpvaUlpd2laVzUwYVhSNVZIbHdaU0k2SWtRaUxDSmxiblJwZEhsRGIyUmxJam9pUVcxdmJGTWlMQ0psYm5SbGNuQnlhWE5sSWpvaVFWQlFWa2xUSWl3aWRISmhibk5FUWlJNklrRlFVRlpKVXlJc0lteHZaMmx1VTJsMFpTSTZJbE13TURBeElpd2ljSEp2Wm1sc1pVbGtJam9pUVVSTlNVNGlMQ0psZUhBaU9qRTNORGN6TWprM01UTTBmUS5NTjRqS00xelQ1NS1OZjZrdHIyWjVHdGRmY3BocFhFeWVQemRwcGFPT2Nv'; // Example token
  showPanel: boolean = false;
  originalData: any[] = [];
  filteredData: any[] = [];

  constructor(private userTaskService: UserTaskService, private snackBar: MatSnackBar) {}

  ngOnInit(): void {
    document.addEventListener('click', this.handleClickOutside.bind(this));
  }

  handleClickOutside(event: MouseEvent) {
    const panel = document.getElementById('pophelp-panel') as HTMLElement;
    const button = event.target as HTMLElement;
    if (panel && !panel.contains(button) && this.showPanel && !button.classList.contains('arrow-button')) {
      this.showPanel = false;
    }
  }

  onSubmit() {
    if (this.taskDetails && this.userCode) {
      const refId = 'prop-2';
      const refSer = 'U-TASK_TEST';
      const userIdAssigned = this.userCode;
      const taskDescr = this.taskDetails;

      this.userTaskService.addUserTask(refId, refSer, userIdAssigned, taskDescr, this.tokenId).subscribe({
        next: (response: any) => {
          console.log('Task added successfully', response);
          this.snackBar.open('Task Added Successfully', 'Close', {
            duration: 4000,
          });
        },
        error: (error: any) => {
          console.error('Error adding task', error);
          this.snackBar.open('Failed! Please try again', 'Close', {
            duration: 3000,
          });
        }
      });
    }
  }

  togglePanel() {
    this.showPanel = !this.showPanel;
    if (this.showPanel) {
      this.fetchDynamicData();
    }
  }

  fetchDynamicData() {
    const fieldName = 'USER_CODE';
    const modName = 'W_USER_TASKS';
    this.userTaskService.getPophelpData(fieldName, modName, this.tokenId).subscribe({
      next: (response: any) => {
        this.originalData = response;
        this.filteredData = response;
      },
      error: (error: any) => {
        console.error('Error fetching data', error);
        this.snackBar.open('Error fetching data', 'Close', {
          duration: 3000,
        });
      }
    });
  }


  filterData(event: Event) {
    const query = (event.target as HTMLInputElement).value.toLowerCase().trim();
    if (!query) {
      this.filteredData = this.originalData; // Reset filter if query is empty
      return;
    }
    this.filteredData = this.originalData.filter(item => 
      (item.CODE?.toLowerCase().includes(query) || item.NAME?.toLowerCase().includes(query))
    );
  }
  
  
  selectUserCode(item: any) {
    this.userCode = item.CODE;
    this.showPanel = false;
  }

  closePanel() {
    this.showPanel = false;
  }
}
