import { Component, OnInit, ViewChild } from '@angular/core';
import { revenueBarChart, statData } from './data';
import { ChartType } from './profile.model';
import { TranslateService } from '@ngx-translate/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { BaseService } from 'src/app/shared/service/base.service';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.scss']
})
export class ProfileComponent implements OnInit {

  revenueBarChart: ChartType;

  userForm!: FormGroup;
  statData;
  userData:any
  timezones:any

  // Settings data
  settings = {
    deviceName: 'userDefined',
    emailNotifications: 'disabled',
    language: '',
    timezone: ''
  };

  constructor(public translate: TranslateService,
    private formBuilder: FormBuilder,
    private modalService: NgbModal,
    private baseService:BaseService
  ) { 
    this.userForm = this.formBuilder.group({
      firstName: ['', Validators.required],
      lastName: [''],
      email: ['', [Validators.required, Validators.email]],
      domainId:[''],
      password:[''],
      repeatPassword:[''],
      newsletter:[false],
      language:[''],
      timezone:['']
    });
  }

  ngOnInit() {
    // fetches the data
    this._fetchData();
    this.getTimeZone();
  }

  /**
   * Fetches the data
   */
  profileImageUrl: string = '';
previewImage: string = '';
selectedFile!: File;

@ViewChild('avatarModal') avatarModal: any;

openAvatarModal() {
  this.modalService.open(this.avatarModal, { centered: true, size: 'sm' , windowClass: 'profile-avatar-modal'});
}
onFileSelect(event: any) {
  const file = event.target.files[0];
  this.loadPreview(file);
}

onFileDrop(event: DragEvent) {
  event.preventDefault();
  const file = event.dataTransfer?.files[0];
  this.loadPreview(file);
}

loadPreview(file: File) {
  if (!file || !file.type.startsWith('image')) return;

  this.selectedFile = file;
  const reader = new FileReader();
  reader.onload = e => this.previewImage = e.target?.result as string;
  reader.readAsDataURL(file);
}

saveProfileImage() {
  const formData = new FormData();
  formData.append('file', this.selectedFile);

  // Call API
  // this.baseService.post('user/upload-profile-photo', formData)
  //   .subscribe(res => {
  //     this.profileImageUrl = this.previewImage;
  //   });
}

  private _fetchData() {
    // this.revenueBarChart = revenueBarChart;
    // this.statData = statData;

    const currentUser = JSON.parse(localStorage.getItem('currentUser'));

    this.baseService.getData(`user/getUsrByHandle/${currentUser.userHandle}`).subscribe(
      (data: any) => {
        if (data) {
          console.log(data);

          this.userData= data.user;
          this.userForm.patchValue({
            firstName: this.userData.name,
            lastName: this.userData.lastName,
            email: this.userData.email,
            domainId: this.userData.userId,          // other fields as necessary
            timezone: String(this.userData.timezone)
          });

          this.userForm.get('domainId')?.disable();
        }
      },
      (err) => {
        console.log(err);
      }
    );
  }

  getTimeZone(){
    this.baseService.getData('system/zones').subscribe(
      (data: any) => {
        if (data) {
          console.log(data);
          this.timezones=data.data
        }
      },
      (err) => {
        console.log(err);
      }
    );
  }

  /**
   * Save profile data
   */
  onSubmit() {
    // Add your save profile logic here

    const formData = new URLSearchParams();
    formData.append('username', this.userData.username);
    formData.append('name', this.userForm.get('firstName').value);
    formData.append('lastName', this.userForm.get('lastName').value);
    formData.append('email', this.userForm.get('email').value);
    formData.append('timezone', this.userForm.get('timezone').value)

    this.baseService.putData(`user/${this.userData.id}`, formData).subscribe(
      response => {
        console.log('Request successful', response);
      },
      error => {
        console.error('Request failed', error);
      }
    );
  }

  /**
   * Save settings data
   */
  saveSettings() {
    // Add your save settings logic here
    console.log('Settings saved', this.settings);
  }

  /**
   * Logout user
   */
  logout() {
    // Add your logout logic here
    console.log('Logged out');
  }
}
