import { CommonModule } from '@angular/common';
import { Component, Optional } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import {
  EditAccountStipulatoriDto,
  FindAccountResDto,
  Stipulatore,
} from '@api/models';
import { RxState } from '@rx-angular/state';
import { ToastMessageOptions } from 'primeng/api';
import { ButtonModule } from 'primeng/button';
import { CalendarModule } from 'primeng/calendar';
import { DatePickerModule } from 'primeng/datepicker';
import { DividerModule } from 'primeng/divider';
import { DropdownModule } from 'primeng/dropdown';
import {
  DialogService,
  DynamicDialogConfig,
  DynamicDialogRef,
} from 'primeng/dynamicdialog';
import { InputSwitchModule } from 'primeng/inputswitch';
import { InputTextModule } from 'primeng/inputtext';
import { MessagesModule } from 'primeng/messages';
import { MultiSelectModule } from 'primeng/multiselect';
import { SelectModule } from 'primeng/select';
import { SkeletonModule } from 'primeng/skeleton';
import { EMPTY, Observable, of } from 'rxjs';
import {
  catchError,
  endWith,
  map,
  startWith,
  switchMap,
  tap,
} from 'rxjs/operators';
import { handleDynamicDialog } from '../../../shared/utils/dynamic-dialog-utils';
import { UtentiService } from '../utenti.service';

export interface ManagestipulatoriDialogComponentState {
  isSaving: boolean;
  isLoading: boolean;
  selectedUser: FindAccountResDto;
  ruoliIsLoading: boolean;
  stipulatori: Stipulatore[];
  stipulatoriIsLoading: boolean;
  stipulatoriAccount: number[];
  stipulatoriAccountIsLoading: boolean;
}

type State = ManagestipulatoriDialogComponentState;

@Component({
  imports: [
    CommonModule,
    SkeletonModule,
    InputSwitchModule,
    FormsModule,
    ButtonModule,
    DividerModule,
    DropdownModule,
    ReactiveFormsModule,
    InputTextModule,
    CalendarModule,
    MultiSelectModule,
    SelectModule,
    DatePickerModule,
    MessagesModule,
  ],
  providers: [RxState, DialogService],
  selector: 'manage-stipulatori-dialog',
  templateUrl: 'manage-stipulatori-dialog.component.html',
  styleUrl: './manage-stipulatori-dialog.component.scss',
})
export class ManagestipulatoriDialogComponent {
  //state = inject(RxState<State>);

  //model$ = this.state.select();

  model$: Observable<ManagestipulatoriDialogComponentState>;

  showTransitionOptions = '500ms';

  messages: ToastMessageOptions[] = [];

  constructor(
    @Optional() readonly dialogRef: DynamicDialogRef,
    @Optional() readonly dialogConfig: DynamicDialogConfig,
    private utentiService: UtentiService,
    public state: RxState<State>,
  ) {
    this.model$ = this.state.select();

    this.state.set({
      isSaving: false,
      isLoading: false,
      stipulatori: [],
      stipulatoriIsLoading: false,
      stipulatoriAccount: [],
      stipulatoriAccountIsLoading: false,
    });

    handleDynamicDialog.bind(this)();

    const fetchStipulatori$ = of(EMPTY).pipe(
      switchMap(() =>
        this.utentiService.getStipulatori().pipe(
          map((res) => ({
            stipulatori: res,
          })),
          catchError(() => of({ stipulatori: [] })),
          startWith({ stipulatoriIsLoading: true }),
          endWith({ stipulatoriIsLoading: false }),
        ),
      ),
    );
    this.state.connect(fetchStipulatori$);

    const fetchStipulatoriByAccountId$ = of(EMPTY).pipe(
      switchMap(() =>
        this.utentiService
          .getStipulatoriByAccountId(this.state.get('selectedUser').id)
          .pipe(
            map((res) => ({
              stipulatoriAccount: res.map((s) => s.id),
            })),
            catchError(() => of({ stipulatoriAccount: [] })),
            startWith({ stipulatoriAccountIsLoading: true }),
            endWith({ stipulatoriAccountIsLoading: false }),
          ),
      ),
    );
    this.state.connect(fetchStipulatoriByAccountId$);
  }

  submitEditStipulatori() {
    const params: EditAccountStipulatoriDto = {
      stipulatori: this.state.get('stipulatoriAccount'),
    };
    const saveAddstipulatore$ = this.utentiService
      .editStipulatori(this.state.get('selectedUser').id, params)
      .pipe(
        catchError((err) => {
          this.messages = [
            {
              severity: 'error',
              summary: 'Attenzione!',
              detail:
                err.status === 400
                  ? err.error.message
                  : "Impossibile modificare gli stipulatori dell'account in questo momento, riprovare più tardi",
            },
          ];
          return of(null);
        }),
        tap((res) => {
          if (!res) return;
          this.dialogRef.close('success');
        }),
        map(() => ({})),
        startWith({ isSaving: true }),
        endWith({ isSaving: false }),
      );
    this.state.connect(saveAddstipulatore$);
  }

  cancelForm() {
    this.dialogRef?.close();
  }
}
