import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {FormBuilder, FormGroup} from "@angular/forms";

@Component({
    selector: 'app-datetime-picker',
    templateUrl: './datetime-picker.component.html',
    styleUrl: './datetime-picker.component.scss'
})
export class DatetimePickerComponent implements OnInit {
    @Input() label: string = 'Date and Time';
    @Input() inputId: string = 'myId';
    @Input() initialValue: string | null = null;
    @Input() readonly: boolean = false;
    @Input() showSeconds: boolean = false;
    @Output() dateTimeChange = new EventEmitter<string | null>();

    form: FormGroup;

    constructor(private fb: FormBuilder) {
        this.form = this.fb.group({
            date: [''],
            time: ['']
        });
    }

    ngOnInit() {
        if (this.initialValue) {
            // Datum als UTC interpretieren
            const date = new Date(this.initialValue);
            this.form.patchValue({
                date: this.formatDate(date),
                time: this.formatTime(date)
            });
        }

        if (this.readonly) {
            this.form.disable();
        }

        this.form.valueChanges.subscribe(() => {
            if (!this.readonly) {
                this.emitDateTime();
            }
        });
    }

    private formatDate(date: Date): string {
        // ISO String verwenden und nur den Datumsteil extrahieren (YYYY-MM-DD)
        return date.toISOString().split('T')[0];
    }

    private formatTime(date: Date): string {
        // Zeit aus ISO String extrahieren
        const timeString = date.toISOString().split('T')[1];

        if (this.showSeconds) {
            // Rückgabe mit Sekunden (HH:MM:SS)
            return timeString.substring(0, 8);
        } else {
            // Nur Stunden und Minuten zurückgeben (HH:MM)
            return timeString.substring(0, 5);
        }
    }

    private emitDateTime() {
        const {date, time} = this.form.value;
        if (date && time) {
            const [year, month, day] = date.split('-');

            // Parse Zeit je nach Format (mit oder ohne Sekunden)
            let hours, minutes, seconds;
            if (this.showSeconds && time.split(':').length > 2) {
                [hours, minutes, seconds] = time.split(':');
            } else {
                [hours, minutes] = time.split(':');
                seconds = '00';
            }

            // Datum in UTC erstellen
            const dateTime = new Date(
                Date.UTC(
                    Number(year),
                    Number(month) - 1,
                    Number(day),
                    Number(hours),
                    Number(minutes),
                    Number(seconds || 0)
                )
            );

            // Als ISO-String formatieren, der automatisch in UTC ist
            const formattedDate = dateTime.toISOString();

            this.dateTimeChange.emit(formattedDate);
        } else {
            this.dateTimeChange.emit(null);
        }
    }
}