import {
	Component,
	ElementRef,
	OnInit,
	ViewChild,
	ViewChildren,
	QueryList,
} from '@angular/core';
import { FormBuilder, FormGroup, FormsModule, NgForm } from '@angular/forms';
import { ToastrService } from 'ngx-toastr';
import Swal from 'sweetalert2';
import { fromEvent, takeUntil } from 'rxjs';
import { TranslatePipe } from '@ngx-translate/core';
import { Unsub } from '../../../shared/class/unsub.class';
import { timeType, timestart, timeend, weekDaysType, weekdays, statusType, status } from '../../../shared/data/businesshours';
import { AdminService } from '../../../shared/services/admin/admin.service';
import { LoaderService } from '../../../shared/services/loader.service';

import { NgSelectModule } from '@ng-select/ng-select';
import { TranslatePipes } from '../../../shared/pipes/translate/translate.pipe';
import { AdminPageHeaderComponent } from '../../../shared/common/pageheader/admin-page-header/admin-page-header.component';

@Component({
	selector: 'app-business-hours',
	templateUrl: './business-hours.component.html',
	styleUrls: ['./business-hours.component.scss'],
	standalone : true,
	imports: [AdminPageHeaderComponent, TranslatePipes, NgSelectModule, FormsModule]
})
export class BusinessHoursComponent extends Unsub implements OnInit {
	@ViewChild('supportIcon') supportIcon!: ElementRef;
	@ViewChild('businesshoursswitch') businesshoursswitch!: ElementRef;
	@ViewChildren('sprukoweeks') sprukoweeks!: QueryList<any>;
	@ViewChildren('businesshourslist') businesshourslist!: QueryList<any>;
	businessData: any;
	form: FormGroup;
	public Src: any;

	public sendingResponse: { [key: string]: boolean } = {};
	timestart: timeType[] = timestart;
	timeend: timeType[] = timeend;
	weekdays: weekDaysType[] = weekdays;
	status: statusType[] = status;
	constructor(
		private adminService: AdminService,
		private toastr: ToastrService,
		public fb: FormBuilder,
		public translate: TranslatePipe,
		loaderService: LoaderService
	) {
		/**
	* This code calls the constructor of the parent class in a subclass. 
	* The super() function is used to initialize the parent class and allows access to its properties and methods. 
	* By calling  super(), the subclass can inherit and use the functionality of the parent class.
	**/
		super(loaderService);
		this.form = this.fb.group({
			image: null,
		});
	}

	ngOnInit(): void {
		this.businessHoursdetails();
		this.adminService.RefreshRquestAdmin$.pipe(
			takeUntil(this.unSubscribe$)
		).subscribe({
			next: () => this.businessHoursdetails()
		});

		const statusChange = fromEvent(
			document.querySelectorAll('.statusChange247'),
			'change'
		);
		statusChange.pipe(takeUntil(this.unSubscribe$)).subscribe({
			next: () => this.businesshoursswitch.nativeElement.checked = false
		});
	}
	businessHoursdetails = () => {
		this.loaderService.showLoader();
		this.adminService
			.businesshour()
			.pipe(takeUntil(this.unSubscribe$))
			.subscribe({
				next: (res) => {
					this.Src = res?.supporticonimageprev;

					this.businessData = res;
					this.loaderService.hideLoader();
				},
				error: () => this.loaderService.hideLoader()
			});
	};
	BusinessHours(ngForm, buttonId) {
		if (ngForm.valid) {
			this.sendingResponse[buttonId] = true;
			const data = ngForm.value;
			this.adminService
				.createBusinesshour(data)
				.pipe(takeUntil(this.unSubscribe$))
				.subscribe({
					next: (res) => {
						this.sendingResponse[buttonId] = false;
						if (res.success) {
							this.toastr.success(this.translate.transform(res.success));
						}
						if (res.error) {
							this.toastr.error(this.translate.transform(res.error.errors.message));
						}
					},
					error: () => {
						this.sendingResponse[buttonId] = false;
					},
				});
		}
	}
	businessofflinemsg(ngForm, buttonId) {
		if (ngForm.valid) {
			this.sendingResponse[buttonId] = true;
			const data = ngForm.value;
			this.adminService
				.bussinesshourOfflinemsg(data)
				.pipe(takeUntil(this.unSubscribe$))
				.subscribe({
					next: (res) => {
						this.sendingResponse[buttonId] = false;
						if (res.success) {
							this.toastr.success(this.translate.transform(res.success));
						}
						if (res.error) {
							this.toastr.error(this.translate.transform(res.error.errors.message));
						}
					},
					error: () => {
						this.sendingResponse[buttonId] = false;
					},
				});
		}
	}

	image(event: any) {
		const file = (event.target as HTMLInputElement)?.files?.[0];
		this.form.patchValue({
			image: file,
		});
	}

	BusinessHrTitle(ngForm: NgForm, buttonId) {
		const formData: any = new FormData();

		formData.append('businesshourssubtitle', ngForm.value.businesshourssubtitle);
		formData.append('businesshourstitle', ngForm.value.businesshourstitle);
		formData.append('supporticon', this.form.controls['image'].value);
		if (
			ngForm.value.businesshoursswitch == true ||
			ngForm.value.businesshoursswitch == 'on'
		) {
			formData.append('businesshoursswitch', 'on');
		}

		this.sendingResponse[buttonId] = true;
		this.adminService
			.createBusinesshourTitle(formData)
			.pipe(takeUntil(this.unSubscribe$))
			.subscribe({
				next: (res) => {
					this.sendingResponse[buttonId] = false;
					if (res.success) {
						this.toastr.success(this.translate.transform(res.success));
						this.form.reset({});
					}
					if (res.error) {
						this.toastr.error(this.translate.transform(res.error.errors.message));
					}
				},
				error: () => {
					this.sendingResponse[buttonId] = false;
				},
			});
	}
	resetBusinessHours() {
		this.businesshourslist?.forEach((element) => {
			element?.nativeElement?.clearModel();
		});
		this.sprukoweeks.forEach((element, ind) => {
			element.nativeElement.value = null;
			this.businessData[`businesshour`][ind]['weeks'] = null;
		});
		const data = {fullhours: "off"}
		this.adminService
			.fullhours(data)
			.pipe(takeUntil(this.unSubscribe$))
			.subscribe({
				next: (res) => {
					if (res.success) {
						this.toastr.success(this.translate.transform('Reseted Successfully'));
					}
					if (res.error) {
						this.toastr.error(this.translate.transform(res.error.errors.message));
					}
				},
			});
	}

	reorder(data, index) {
		return data.slice(index).concat(data.slice(0, index));
	}

	daySort(val) {
		const dayListArr = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
		const startDay = val.value;
		if (startDay) {
			for (let i = 0; i <= dayListArr.length; i++) {
				if (dayListArr[i] === startDay) {
					const newDayList = dayListArr.slice(i).concat(dayListArr.slice(0, i));
					this.sprukoweeks.forEach((element, ind) => {
						element.nativeElement.value = newDayList[ind + 1];
						this.businessData[`businesshour`][ind + 1]['weeks'] =
							newDayList[ind + 1];
					});
				}
			}
		}
	}

	businesslogodelete() {
		const PostData = {

			supporticonimage: 'supporticonimage',
		};

		Swal.fire({
			icon: 'warning',
			title: this.translate.transform('Are you sure ?'),
			text: this.translate.transform('Your will not be able to recover!'),
			showCancelButton: true,
			confirmButtonColor: '#6259ca',
			cancelButtonColor: '#f11541',
			confirmButtonText: this.translate.transform('Yes, delete it!'),
			cancelButtonText: this.translate.transform('Close'),
			reverseButtons: true,
		}).then((result: any) => {
			if (result.isConfirmed) {
				this.adminService
					.businesslogodelete(PostData)
					.pipe(takeUntil(this.unSubscribe$))
					.subscribe({
						next: (res) => {
							this.toastr.success(this.translate.transform(res.success));
							this.supportIcon.nativeElement.value = '';
						},
					});
			}
		});
	}

	businesshoursswitch247(ele) {
		let status = this.businesshoursswitch.nativeElement.checked;
		
        Swal.fire({
            icon: 'warning',
            title: this.translate.transform('Are you sure you want to continue?'),
            text: this.translate.transform(this.businessData?.['24hoursbusinessswitch'] =='off' ? 'If you enable this all business hours are set to be 24/7 format, then holidays are not showing anymore.' : 'If you disable this, the 24/7 timings are disclosed you can change business hour timings accordingly to your concern.'),
            showCancelButton: true,
            confirmButtonColor: '#6259ca',
            cancelButtonColor: '#f11541',
            confirmButtonText: this.translate.transform('Yes, reset it!'),
            cancelButtonText: this.translate.transform('Close'),
            reverseButtons: true,
        }).then((result: any) => {
            if (result.isConfirmed) {
				if (ele.checked) {
					const data = {fullhours : 'on'};
					this.adminService
						.fullhours(data)
						.pipe(takeUntil(this.unSubscribe$))
						.subscribe({
							next: (res) => {
								if (res.success) {
									this.toastr.success(this.translate.transform(res.success));
								}
								if (res.error) {
									this.toastr.error(this.translate.transform(res.error.errors.message));
								}
							},
							error: () => {
							},
						});
				} else {
					this.resetBusinessHours();
				}
            }else{
				this.businesshoursswitch.nativeElement.checked = !status;
				
			}
        });
	}
	remove247() {
		this.businesshoursswitch.nativeElement.checked = false;
	}
}
