import { NgIf } from "@angular/common";
import { Component, ElementRef, OnInit, ViewChild } from "@angular/core";
import { FormGroup, FormsModule, ReactiveFormsModule } from "@angular/forms";
import { ActivatedRoute } from "@angular/router";
import { api } from "@enums/api.enum";
import { Roots } from "@enums/root.enum";
import { CommonResponse, Member, ProfileData } from "@interfaces/common";
import { SanghMemberForm } from "@interfaces/form";
import { IonicModule, NavController } from "@ionic/angular";
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 { UtilityService } from "@services/utility.service";

@Component({
    selector: 'app-sangh-information',
    templateUrl: './sangh-member-card.page.html',
    styleUrls: ['./sangh-member-card.page.scss'],
    standalone: true,
    imports: [IonicModule, FormsModule, ReactiveFormsModule, NgIf]
})
export class SanghMemberCardPage implements OnInit {
    @ViewChild('Location', { static: false }) Location: ElementRef;
    longitude = '';
    latitude = '';
    currentLocation: string;
    sanghId: string
    sanghMemberForm: FormGroup<SanghMemberForm>;
    haveMemberCard = false;
    memberDetail: Member;
    userDetail: ProfileData;
    loader = false;

    constructor(
        private utilityService: UtilityService,
        private cRoute: ActivatedRoute,
        private navCtrl: NavController,
        public santService: SantInfoService,
        private cameraGalleryService: CameraGalleryService,
        private alert: AlertService,
        private httpRequestService: HttpRequestService
    ) {
        this.sanghId = this.cRoute.snapshot.paramMap.get('id');
    }

    ngOnInit(): void {
        this.sanghMemberForm = this.santService.memberCardForm;
    }

    ionViewWillEnter() {
        this.getUserDetails();
        this.getSanghCard();
    }

    getSanghCard() {
        this.httpRequestService.get(api.sangCard.replace('{id}', this.sanghId)).then((res: CommonResponse) => {
            if (res.data) {
                this.memberDetail = res.data[0];
                this.haveMemberCard = this.memberDetail?.profile_image ? true : false;
                this.sanghMemberForm.controls.memberId.setValue(res.data[0].member_id);
                if (this.memberDetail?.user?.user_detail[0]?.location) {
                    this.setAddress(this.memberDetail?.user?.user_detail[0]?.location);
                }
            }
        });
    }

    getUserDetails(): void {
        this.httpRequestService.get(api.shravakProfile).then((res: CommonResponse) => {
            if (res.data) {
                this.userDetail = res.data;
                this.sanghMemberForm.controls.fullName.setValue(res.data.name ?? '');
                this.sanghMemberForm.controls.address.setValue(res.data.location ?? '');
                this.latitude = res.data.latitude ?? '';
                this.longitude = res.data.latitude ?? '';
            }
        });
    }

    setAddress(location: string): void {
        this.utilityService.getAddress(location).subscribe(res => {
            const { city, state } = this.getCityAndState(res[0].address_components);
            this.currentLocation = city + ',' + state;
        });
    }

    getCityAndState(addressComponents: any): { city: string, state: string } {
        let city = '';
        let state = '';

        addressComponents.forEach(component => {
            const types = component.types;
            if (types.includes('locality')) {
                city = component.long_name;
            }
            if (types.includes('administrative_area_level_1')) {
                state = component.long_name;
            }
        });

        return { city, state };
    }

    initAutocomplete(): void {
        this.utilityService.createAutocomplete(this.Location.nativeElement, []).subscribe((details) => {
            this.longitude = details.geometry.location.lng();
            this.latitude = details.geometry.location.lat();
            this.sanghMemberForm.controls.address.setValue(details.formatted_address ?? '');
        });
    }

    selectImages() {
        this.cameraGalleryService.selectImage(512, 512, true).then((imageData: { imgString: string; itemImage: Blob }) => {
            if (this.utilityService.isMaxFileSize(imageData?.itemImage?.size)) {
                this.alert.showToasterError('Image size exceeds 2MB limit. Please choose a smaller file');
                return;
            }
            this.sanghMemberForm.controls.profile_url.setValue(imageData.imgString);
            this.sanghMemberForm.controls.profile.setValue(imageData.itemImage);
        });
    }

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

    removeImage(): void {
        this.sanghMemberForm.controls.profile_url.setValue(null);
        this.sanghMemberForm.controls.profile.setValue(null);
    }

    onSubmit(): void {
        if (!this.sanghMemberForm.valid) {
            this.sanghMemberForm.markAllAsTouched();
            return;
        }

        if (!this.sanghMemberForm.controls.profile_url.value) {
            this.alert.showToasterError('Profile photo is required');
            return;
        }
        const formValue = this.sanghMemberForm.value;

        const formData = new FormData();
        formData.append('name', formValue.fullName);
        formData.append('sangh_id', this.sanghId);
        formData.append('member_id', this.memberDetail?.member_id?.toString());
        formData.append('location', formValue.address);
        this.longitude && formData.append('longitude', this.longitude.toString());
        this.latitude && formData.append('latitude', this.latitude.toString());

        if (formValue.profile) {
            formData.append('profile_image', formValue.profile);
        }

        this.loader = true;
        this.httpRequestService.post(api.memberCardSangh, formData).then(() => {
            this.santService.memberCardForm.reset();
            this.loader = false;
            this.alert.showToaster('Member card details updated');
            this.getSanghCard();
        }).catch(() => {
            this.loader = false;
        });
    }

    async onPrevious(): Promise<void> {
        if (this.haveMemberCard) {
            this.navCtrl.navigateForward(Roots.page + '/' + Roots.sanghProfile.replace(':sanghId', this.sanghId));
        } else {
            const isYes = await this.utilityService.presentConfirm(
                'Are you sure want to exit?',
                'No', 'Yes'
            );
            if (isYes) {
                this.santService.memberCardForm.reset();
                this.navCtrl.navigateForward(Roots.page + '/' + Roots.sanghProfile.replace(':sanghId', this.sanghId));
            }
        }
    }
}