import { NgClass, NgIf } from '@angular/common';
import { Component, Input, OnInit } from '@angular/core';
import { FormControl, FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import { api } from '@enums/api.enum';
import { CommonResponse, SanghData, UserData } from '@interfaces/common';
import { JoinSanghForm } from '@interfaces/form';
import { IonicModule } from '@ionic/angular';
import { AlertService } from '@services/alert.service';
import { HttpRequestService } from '@services/http-request.service';
import { UtilityService } from '@services/utility.service';

@Component({
  selector: 'app-join-sangh-button',
  templateUrl: './join-sangh-button.component.html',
  styleUrls: ['./join-sangh-button.component.scss'],
  standalone: true,
  imports: [NgIf, IonicModule, FormsModule, ReactiveFormsModule, NgClass],
})
export class JoinSanghButtonComponent implements OnInit {
  @Input() sangh: any;
  @Input() userData: UserData;
  @Input() page: string;
  joinSanghForm: FormGroup<JoinSanghForm>;
  isModalOpen = false;

  constructor(
    private httpRequestService: HttpRequestService,
    private alert: AlertService,
    private utilityService: UtilityService
  ) { }

  ngOnInit(): void {
    this.joinSanghForm = new FormGroup<JoinSanghForm>({
      joinType: new FormControl('member'),
      roleName: new FormControl(null)
    });
    this.onTypeChange();
  }

  joinSangh(sangh: SanghData) {
    if (this.sangh.sangh_member_status === 3) {
      this.cancelSanghRequest(sangh);
    } else {
      this.isModalOpen = true;
    }
  }

  onTypeChange() {
    this.joinSanghForm.get('roleName').addValidators([Validators.required]);
    if (this.joinSanghForm.value.joinType === 'member') {
      this.joinSanghForm.get('roleName').clearValidators();
    }
    this.joinSanghForm.get('roleName').updateValueAndValidity();
  }

  confirmJoin() {
    this.joinSanghForm.markAllAsTouched();

    if (this.joinSanghForm.invalid) { return; }

    this.alert.showLoader();
    this.httpRequestService.post(api.addMemberForSangh, {
      sangh_id: this.sangh.id,
      user_id: [this.userData.id],
      is_join: 1,
      ...this.joinSanghForm.value.joinType === 'committee' && {
        core_committee: 1,
        role: this.joinSanghForm.value.roleName,
      }
    }).then((res: any) => {
      this.sangh.sangh_member_status = 3;
      this.alert.showToaster(res.message);
    }).finally(() => {
      this.isModalOpen = false;
      this.alert.hideLoader();
    });
  }

  async cancelSanghRequest(sangh: SanghData) {
    const isYes = await this.utilityService.presentConfirm(
      'Are you sure about cancel this request?',
      'No', 'Yes', 'Cancel Request'
    );
    if (isYes) {
      this.alert.showLoader();
      this.httpRequestService.post(api.acceptDeclineSanghRequest, {
        sangh_id: sangh.id,
        user_id: this.userData.id,
        status: 2,
      }).then((res: any) => {
        sangh.sangh_member_status = 0;
        this.alert.showToaster(res.message);
      }).finally(() => this.alert.hideLoader());
    }
  }

  acceptDecline() {
    this.utilityService.presentAcceptDecline(`Please confirm`)
      .then(action => {
        if (action) {
          this.alert.showLoader();
          this.httpRequestService.post(api.acceptDeclineSanghRequest, {
            sangh_id: this.sangh.id,
            user_id: this.userData.id,
            status: action, // 1-accept, 2-decline/cancel
            is_commiittee: this.sangh.is_member === 0 ? 0 : 1,
          }).then((res: CommonResponse) => {
            this.alert.showToaster(res.message);
            this.sangh.sangh_member_status = (action === 1 ? 1 : 0); // 1-accept, 0-reset
          }).finally(() => {
            this.alert.hideLoader();
          });
        }
      });
  }
}
