import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { MenumaintanceService } from 'src/app/services/admin/menumaintance.service';
import { Rn_Forms_Setup } from 'src/app/models/fnd/Rn_Forms_Setup';
import { DynamicformService } from '../services/dynamicform.service';
@Component({
  selector: 'app-alldynamicform',
  templateUrl: './alldynamicform.component.html',
  styleUrls: ['./alldynamicform.component.scss']
})
export class AlldynamicformComponent implements OnInit {
  rowSelected: any = {};
  modaldelete = false;
  loading = false;
  data;
  error;
  selected: any[] = [];
  constructor(private dynamicservice: DynamicformService,
    private router: Router,
    private toastr: ToastrService,
    private route: ActivatedRoute,
    private menumaintanceService: MenumaintanceService,

  ) { }

  ngOnInit(): void {
    this.getall();
  }
  getall() {
    this.dynamicservice.getAll().subscribe((data) => {
      this.data = data.items;
      this.data = [...this.data].reverse();
      console.log('dynmic data ', data);
      if (data.length == 0) {
        this.error = "No data Available plz add if Required";
        console.log(this.error)
      }
    }, (error) => {
      console.log(error);
      if (error) {
        this.error = "Server Error";
      }
    })
  }
  goToAdd() {
    this.router.navigate(["../add"], { relativeTo: this.route });
  }
  goToEdit(id: number) {
    console.log("goToEdit() id = " + id);
    this.router.navigate(["../edit/" + id], { relativeTo: this.route });
  }
  goToForm(id: number) {
    this.router.navigate(['/cns-portal/dynamicform1'], { queryParams: { form_id: id } });

  }
  form_id;
  alertType: string;
  alertMessage: string = "";
  alert = [
    { type: "success", message: "Build Successfully" },
    { type: "danger", message: "Some error Happens" },
  ];
  buildDynamicForm(id) {
    this.form_id = id;
    console.log("buildDynamicForm() Form_id = " + this.form_id);
    if (this.form_id === null) {
      this.alertType = this.alert[1].type;
      this.alertMessage = "form_code is null";
      return;
    }

    // Fetch form definition to check relation
    this.dynamicservice.getById(id).subscribe(
      (form: Rn_Forms_Setup) => {
        if (form && form.related_to === 'Menu') {
          this.createMenuForForm(form);
        } else {
          // Standard behavior for non-Menu forms
          console.log("Form construction handled by frontend viewer.");
          this.alertType = this.alert[0].type;
          this.alertMessage = this.alert[0].message;
          this.toastr.success("Form Ready for Viewing (Frontend Render)", "Success");
        }
      },
      (err) => {
        console.error(err);
        this.toastr.error("Failed to fetch form details");
      }
    );
  }


  createMenuForForm(form: Rn_Forms_Setup) {
    // Construct Payload for Menu Creation
    // Requirement: menuId = 12832
    // Link: dynamicform1?form_id={id}

    const menuPayload = {
      menuId: 12832,
      menuItemDesc: form.form_name,
      itemSeq: 1, // Default sequence
      moduleName: form.form_name,
      status: 'Enable',
      main_menu_action_name: `dynamicform1/${form.form_id}`
    };

    // Check for duplicate menu
    this.menumaintanceService.getLatestMenu(12832, menuPayload.moduleName, menuPayload.main_menu_action_name)
      .subscribe(
        (existingMenu) => {
          if (existingMenu) {
            console.log('Menu already exists:', existingMenu);
            this.toastr.info('Menu Already Created');
          } else {
            // Not found, create it
            this.proceedToCreateMenu(menuPayload);
          }
        },
        (err) => {
          console.error('Error checking duplicate menu', err);
          // Optional: Proceed if error is 404, but angular http might treat 404 as error
          // If backend returns null for not found, we fall into if(existingMenu) else block.
          // If backend throws error for not found, we handle here.
          // Assuming backend returns empty body or null 200 OK if not found is ideal, 
          // but if it throws exception, we might want to proceed? 
          // Safe bet: if error, try to create or warn. 
          // Given msg "menu already created" requirement, let's assume valid check.
          // Let's assume error means "Not Found" -> Create
          this.proceedToCreateMenu(menuPayload);
        }
      );
  }

  proceedToCreateMenu(menuPayload: any) {
    console.log('Building Menu for Form:', menuPayload);

    this.menumaintanceService.create1(menuPayload).subscribe(
      (data) => {
        console.log('Menu Item Created:', data);
        this.toastr.success('Menu Item Created. Syncing...');

        // 3. Sync
        this.syncMenu(menuPayload);
      },
      (err) => {
        console.error('Failed to create menu item', err);
        this.toastr.error('Failed to create menu item');
      }
    );
  }

  syncMenu(payload: any) {
    const syncPayload = { ...payload };
    if (syncPayload.subMenus && syncPayload.subMenus !== 0) {
      syncPayload.subMenus = [];
    }

    this.menumaintanceService.sink(12832, syncPayload).subscribe(
      (data) => {
        this.toastr.success('Menu Synced Successfully');
        this.toastr.info('Form is now accessible via Menu');
      },
      (err) => {
        console.error('Sync failed', err);
        this.toastr.error('Menu Sync Failed');
      }
    );
  }

  onDelete(row) {
    this.rowSelected = row;
    this.modaldelete = true;
  }
  delete(id) {
    this.modaldelete = false;
    console.log("in delete  " + id);
    this.dynamicservice.delete(id).subscribe((data) => {
      console.log(data);
      this.ngOnInit();
      if (data.body) {
        this.toastr.success('Deleted successfully');
      }
    }, (error) => {
      console.log('Error in adding data...', +error);
      if (error) {
        this.toastr.error('Not Deleted Data Getting Some Error');
      }
    });
  }
}
