import { Component, inject, ChangeDetectionStrategy, signal, OnInit, computed } from '@angular/core';
import { UserRep } from '../../../models/user-management.api.models';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { UserRepService } from '../../../services/api/user-representation.service';
import { GroupUpdateFormComponent } from '../group-update-form/group-update-form.component';
import { JsonPipe } from '@angular/common';
import { FormControl, FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { DateAdapter, MAT_DATE_LOCALE, provideNativeDateAdapter } from '@angular/material/core';
import { MatDatepickerIntl, MatDatepickerModule } from '@angular/material/datepicker';
import { MatFormFieldModule } from '@angular/material/form-field';
import Swal from 'sweetalert2';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { provideMomentDateAdapter } from '@angular/material-moment-adapter';
import { MatInputModule } from '@angular/material/input';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import 'moment/locale/de';

@Component({
  selector: 'app-rep-create-form',
  standalone: true,
  providers: [
    provideNativeDateAdapter(),
    { provide: MAT_DATE_LOCALE, useValue: 'de-DE' },
    provideMomentDateAdapter()
  ],
  imports: [MatFormFieldModule, MatDatepickerModule, FormsModule, ReactiveFormsModule, JsonPipe, MatButtonModule, MatIconModule, MatInputModule, MatSlideToggleModule],
  templateUrl: './rep-create-form.component.html',
  styleUrl: './rep-create-form.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class RepCreateFormComponent implements OnInit {

  readonly userRep: UserRep;
  readonly afterCreation: (any: any) => any;
  readonly userRepService: UserRepService = inject(UserRepService);
  readonly dialogRef: MatDialogRef<GroupUpdateFormComponent> = inject(MatDialogRef<GroupUpdateFormComponent>);
  readonly range = new FormGroup({
    start: new FormControl<Date | null>(null),
    end: new FormControl<Date | null>(null),
  });
  private readonly _locale = signal(inject<unknown>(MAT_DATE_LOCALE));
  private readonly _adapter = inject<DateAdapter<unknown, unknown>>(DateAdapter);
  private readonly _intl = inject(MatDatepickerIntl);
  termless: boolean = false;

  constructor() {
    const dialogData: { userRep: UserRep, afterCreation: (any: any) => any } = inject(MAT_DIALOG_DATA)
    this.userRep = dialogData.userRep;
    this.afterCreation = dialogData.afterCreation;
  }

  ngOnInit(): void {
    //update close button label
    this._intl.closeCalendarLabel = 'Kalender schließen';
    this._intl.changes.next();

    //set local
    this._locale.set('de');
    this._adapter.setLocale(this._locale());
  }

  readonly dateFormatString = computed(() => {
    if (this._locale() === 'de-DE') {
      return 'dd.mm.yyyy';
    }
    return '';
  });

  create() {
    const validFrom = this.range.value.start;
    const validTo = this.range.value.end;

    if ((!validFrom || !validTo) && !this.termless) {
      Swal.fire({
        icon: "error",
        title: "Oops...",
        text: "Bitte geben Sie einen gültigen Datumsbereich ein oder wählen Sie unbefristet!",
      });

      return;
    }

    if (!this.termless) {
      this.userRep.validFrom = validFrom!;
      this.userRep.validTo = validTo!;
    }

    this.userRepService.create(this.userRep).subscribe({
      next: (res) => {
        this.afterCreation({ successful: res });
        this.dialogRef.close();
      },
      error: (error) => {
        this.afterCreation({ error: error });
      }
    });
  }
}
