import { NgClass, NgFor, NgIf } from '@angular/common';
import { Component, OnInit, ViewChild } from '@angular/core';
import { FormGroup, ReactiveFormsModule } from '@angular/forms';
import { Browser } from '@capacitor/browser';
import { IonicSelectableComponent } from '@components/ionic-selectable/ionic-selectable.component';
import { api } from '@enums/api.enum';
import { CertificateStatus, CertificateStep, constants } from '@enums/constants.enum';
import { GJainStorage } from '@enums/gjain-storage.enum';
import { Roots } from '@enums/root.enum';
import { CertificateDetail, CommonResponse, Hospital, Photo, PhotoDetail, ProfileData } from '@interfaces/common';
import { CertificateForm, CertificateTermConditionForm } from '@interfaces/form';
import { IonModal, IonicModule, NavController } from '@ionic/angular';
import { AddHoursPipe } from '@pipes/add-hours.pipe';
import { SafeUrlPipe } from '@pipes/safe-url.pipe';
import { AlertService } from '@services/alert.service';
import { CameraGalleryService } from '@services/camera-gallery.service';
import { HttpRequestService } from '@services/http-request.service';
import { SantInfoService } from '@services/sant-info.service';
import { StateManagementService } from '@services/state-management.service';
import { UtilityService } from '@services/utility.service';
import { CertificateTermPolicyComponent } from '../certificate-term-policy/certificate-term-policy.component';
@Component({
    selector: 'app-discount-certificate',
    templateUrl: './discount-certificate.page.html',
    styleUrls: ['./discount-certificate.page.scss'],
    standalone: true,
    imports: [IonicModule, ReactiveFormsModule, CertificateTermPolicyComponent, IonicSelectableComponent, AddHoursPipe, NgFor, NgClass, NgIf, SafeUrlPipe]
})
export class DiscountCertificatePage implements OnInit {
    @ViewChild('confirmModel') confirmModel: IonModal;
    @ViewChild('confirmCancelModel') confirmCancelModel: IonModal;
    @ViewChild('confirmDetailModel') confirmDetailModel: IonModal;

    readonly certificateStep = CertificateStep;
    readonly certificateStatus = CertificateStatus;

    hospitalList: Hospital[] = [];
    hospitalFacility: string[] = constants.medicalReason;
    certificateInformationForm: FormGroup<CertificateForm>;
    certificateTermConditionForm: FormGroup<CertificateTermConditionForm>;
    photo = new Photo();
    pageNo = CertificateStep.home;
    certificateDetail: CertificateDetail;

    constructor(
        public santService: SantInfoService,
        private cameraGalleryService: CameraGalleryService,
        public utilityService: UtilityService,
        private httpRequestService: HttpRequestService,
        private alert: AlertService,
        private stateManagementService: StateManagementService,
        private navCtrl: NavController
    ) { }

    ngOnInit(): void {
        this.certificateInformationForm = this.santService.certificateForm;
        this.certificateTermConditionForm = this.santService.certificateTermConditionForm;

        this.getUserDetails();
        this.getHospitalList();
    }

    ionViewWillEnter(): void {
        this.getCertificateDetail();
    }

    getUserDetails(): void {
        this.stateManagementService.storage.get(GJainStorage.userData).then((res: ProfileData) => {
            if (res) {
                this.certificateInformationForm.controls.email.setValue(res.email);
                this.certificateInformationForm.controls.fullName.setValue(res.name);
            }
        });
    }

    getCertificateDetail(): void {
        this.httpRequestService.get(api.certificateDetail).then((res: CommonResponse) => {
            this.certificateDetail = res.data;
            this.certificateDetail && this.setFormValue();
        })
    }

    setFormValue(): void {
        this.certificateInformationForm.setValue({
            hospital: this.certificateDetail.hospital_id,
            fullName: this.certificateDetail.full_name,
            email: this.certificateDetail.email,
            address: this.certificateDetail.address,
            aadharNumber: this.certificateDetail.aadhar_card_number,
            medicalDescription: this.certificateDetail.medical_problem,
        });
    }

    getHospitalList(): void {
        this.httpRequestService.get(api.hospitalList).then((res: CommonResponse) => {
            this.hospitalList = res.data;
        })
    }

    onSubmit(): void {
        if (this.pageNo === this.certificateStep.home) {
            if (!this.certificateTermConditionForm?.value?.termCondition) {
                this.alert.showToasterError('Please agree terms and conditions');
                return;
            }
            this.certificateTermConditionForm.reset();
            this.pageNo = this.certificateStep.info;
        } else {
            if (this.certificateInformationForm?.invalid) {
                this.certificateInformationForm.markAllAsTouched();
                return;
            }
            if (!this.photo?.aadharFront?.url) {
                this.alert.showToasterError('Aadhar card front image is required');
                return;
            }

            if (!this.photo?.aadharBack?.url) {
                this.alert.showToasterError('Aadhar card back image is required');
                return;
            }
            this.confirmDetailModel.isOpen = true;
        }
    }

    onPrevious(): void {
        if (this.pageNo === CertificateStep.home) {
            this.onCancel()
        }
        else {
            this.onCancel(true)
        }
    }

    dismissModel(isGenerated = false): void {
        if (isGenerated) {
            this.pageNo = this.certificateStep.home;
            this.resetForm();
        }
        this.confirmModel.isOpen = false;
        this.getCertificateDetail();
    }

    onConfirmDetail(confirm: boolean): void {
        this.confirmDetailModel.isOpen = false;
        if (confirm) {
            const params = this.getParams();
            this.httpRequestService.post(api.certificate, params).then(res => {
                if (res) {
                    this.confirmModel.isOpen = true;
                }
            })
        }
    }

    getParams() {
        const certificateInfoForm = this.certificateInformationForm.value;

        const formData = new FormData();
        formData.append('hospital_id', certificateInfoForm.hospital);
        formData.append('full_name', certificateInfoForm.fullName);
        formData.append('address', certificateInfoForm.address);
        formData.append('email', certificateInfoForm.email);
        formData.append('medical_problem', certificateInfoForm.medicalDescription);
        formData.append('aadhar_card_number', certificateInfoForm.aadharNumber);

        this.photo?.aadharFront?.imageData && formData.append('aadhar_card_front_photo', this.photo.aadharFront.imageData);
        this.photo?.aadharBack?.imageData && formData.append('aadhar_card_back_photo', this.photo.aadharBack.imageData);
        this.certificateDetail && formData.append('id', this.certificateDetail.id);

        return formData;
    }

    async downloadCertificate(): Promise<void> {
        await Browser.open({ url: this.certificateDetail.pdf_url });
    }

    profileView(url: string): void {
        this.utilityService.imagePreview(url);
    }

    removeImage(front = false): void {
        if (front) {
            this.photo.aadharFront = new PhotoDetail();
        }
        else {
            this.photo.aadharBack = new PhotoDetail();
        }
    }

    onCancel(home = false): void {
        if (home) {
            this.confirmCancelModel.isOpen = true;
        }
        else {
            this.navCtrl.navigateForward([Roots.page]);
            this.resetForm();
        }
    }

    resetForm(): void {
        this.certificateInformationForm.reset();
        this.photo = new Photo();
    }

    onConfirmCancel(cancel = false) {
        if (cancel) {
            this.pageNo = CertificateStep.home;
            this.resetForm();
        }
        this.confirmCancelModel.isOpen = false;
    }

    termsPolicy(terms = false) {
        if (terms) {
            this.navCtrl.navigateForward([Roots.page + '/' + Roots.termsPolicy]);
        } else {
            this.navCtrl.navigateForward([Roots.page + '/' + Roots.visibilityPolicy]);
        }
    }

    selectImages(isAadhar = 0) {
        if (isAadhar) {
            this.cameraGalleryService.selectImage(512, 512, false).then((imageData: { imgString: string; itemImage: Blob }) => {
                const photo = new PhotoDetail();
                photo.url = imageData.imgString;
                photo.imageData = imageData.itemImage;
                if (isAadhar === 1) {
                    this.photo.aadharFront = photo;
                } else {
                    this.photo.aadharBack = photo;
                }
            });
        }
    }
}
