import { Component, OnDestroy } from '@angular/core';
import { FormGroup, ReactiveFormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatNativeDateModule } from '@angular/material/core';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { MatTooltipModule } from '@angular/material/tooltip';
import {
	MeetRoomAutoDeletionPolicy,
	MeetRoomDeletionPolicyWithMeeting,
	MeetRoomDeletionPolicyWithRecordings,
	MeetRoomOptions
} from '@openvidu-meet/typings';
import { Subject, takeUntil } from 'rxjs';
import { RoomWizardStateService } from '../../../../services';

@Component({
    selector: 'ov-room-details',
    imports: [
        ReactiveFormsModule,
        MatButtonModule,
        MatIconModule,
        MatInputModule,
        MatFormFieldModule,
        MatDatepickerModule,
        MatNativeDateModule,
        MatSelectModule,
        MatTooltipModule
    ],
    templateUrl: './room-details.component.html',
    styleUrl: './room-details.component.scss'
})
export class RoomWizardRoomDetailsComponent implements OnDestroy {
	roomDetailsForm: FormGroup;

	// Arrays for time selection
	hours = Array.from({ length: 24 }, (_, i) => ({ value: i, display: i.toString().padStart(2, '0') }));
	minutes = Array.from({ length: 60 }, (_, i) => ({ value: i, display: i.toString().padStart(2, '0') }));

	meetingPolicyOptions = [
		{
			value: MeetRoomDeletionPolicyWithMeeting.FORCE,
			label: 'Force',
			description:
				'The meeting will be ended, and the room will be deleted without waiting for participants to leave.'
		},
		{
			value: MeetRoomDeletionPolicyWithMeeting.WHEN_MEETING_ENDS,
			label: 'When meeting ends',
			description: 'The room will be deleted when the meeting ends.'
		}
	];
	recordingPolicyOptions = [
		{
			value: MeetRoomDeletionPolicyWithRecordings.FORCE,
			label: 'Force',
			description: 'The room and its recordings will be deleted.'
		},
		{
			value: MeetRoomDeletionPolicyWithRecordings.CLOSE,
			label: 'Close',
			description: 'The room will be closed instead of deleted, maintaining its recordings.'
		}
	];

	private destroy$ = new Subject<void>();

	constructor(private wizardService: RoomWizardStateService) {
		const currentStep = this.wizardService.currentStep();
		this.roomDetailsForm = currentStep!.formGroup;

		this.roomDetailsForm.valueChanges.pipe(takeUntil(this.destroy$)).subscribe((value) => {
			this.saveFormData(value);
		});
	}

	ngOnDestroy() {
		this.destroy$.next();
		this.destroy$.complete();
	}

	private saveFormData(formValue: any) {
		let autoDeletionDateTime: number | undefined = undefined;
		let autoDeletionPolicy: MeetRoomAutoDeletionPolicy | undefined = undefined;

		// If date is selected
		if (formValue.autoDeletionDate) {
			// Combine date with time
			const date = new Date(formValue.autoDeletionDate);
			date.setHours(formValue.autoDeletionHour ?? 23);
			date.setMinutes(formValue.autoDeletionMinute ?? 59);
			date.setSeconds(0);
			date.setMilliseconds(0);
			autoDeletionDateTime = date.getTime();

			// Set auto deletion policy
			autoDeletionPolicy = {
				withMeeting: formValue.autoDeletionPolicyWithMeeting,
				withRecordings: formValue.autoDeletionPolicyWithRecordings
			};
		}

		const stepData: Partial<MeetRoomOptions> = {
			roomName: formValue.roomName,
			autoDeletionDate: autoDeletionDateTime,
			autoDeletionPolicy
		};

		// Always save to wizard state (including when values are cleared)
		this.wizardService.updateStepData('roomDetails', stepData);
	}

	get minDate(): Date {
		const now = new Date();
		now.setHours(now.getHours() + 1, 0, 0, 0); // Set to 1 hour in the future
		return now;
	}

	get hasDateSelected(): boolean {
		return !!this.roomDetailsForm.get('autoDeletionDate')?.value;
	}

	getFormattedDateTime(): string {
		const formValue = this.roomDetailsForm.value;
		if (!formValue.autoDeletionDate) {
			return '';
		}

		const date = new Date(formValue.autoDeletionDate);
		const hour = formValue.autoDeletionHour ?? 23;
		const minute = formValue.autoDeletionMinute ?? 59;

		date.setHours(hour);
		date.setMinutes(minute);

		return date.toLocaleString('en-US', {
			weekday: 'long',
			year: 'numeric',
			month: 'long',
			day: 'numeric',
			hour: '2-digit',
			minute: '2-digit',
			hour12: false
		});
	}

	clearDeletionDate() {
		this.roomDetailsForm.patchValue({
			autoDeletionDate: null,
			autoDeletionHour: 23,
			autoDeletionMinute: 59
		});
	}

	getMeetingPolicyDescription(): string {
		const selectedValue = this.roomDetailsForm.get('autoDeletionPolicyWithMeeting')?.value;
		const option = this.meetingPolicyOptions.find((opt) => opt.value === selectedValue);
		return option?.description || '';
	}

	getRecordingPolicyDescription(): string {
		const selectedValue = this.roomDetailsForm.get('autoDeletionPolicyWithRecordings')?.value;
		const option = this.recordingPolicyOptions.find((opt) => opt.value === selectedValue);
		return option?.description || '';
	}
}
