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) {
      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 {
    return date.toLocaleDateString('en-CA');
  }

    private formatTime(date: Date): string {
        if (this.showSeconds) {
            return date.toLocaleTimeString('en-GB', { hour12: false });
        } else {
            // Nur Stunden und Minuten zurückgeben
            return date.toLocaleTimeString('en-GB', {
                hour12: false,
                hour: '2-digit',
                minute: '2-digit'
            });
        }
    }

    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';
            }

            const dateTime = new Date(
                Number(year),
                Number(month) - 1,
                Number(day),
                Number(hours),
                Number(minutes),
                Number(seconds || 0)
            );

            // Format the date to match the loaded format
            const formattedDate = dateTime.toLocaleString('sv-SE', { timeZone: 'Europe/Berlin' }).replace(' ', 'T') + '+02:00';

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