import { inject, Injectable } from '@angular/core';

import { Action, Selector, State, StateContext, Store } from '@ngxs/store';
import { tap } from 'rxjs';

import { ClearCartAction } from '../action/cart.action';
import {
  ClearZoneAction,
  GetZoneAction,
  IsSelectedZoneAction,
  SaveLocationAction,
} from '../action/zone.action';
import { ITag } from '../interface/tag.interface';
import { ZoneService } from '../services/zone.service';

export class ZoneStateModel {
  zone = {
    data: [] as ITag[],
    total: 0,
  };
  selectedZone: number[];
  location: string;
  isZoneSelected: boolean;
}

@State<ZoneStateModel>({
  name: 'zone',
  defaults: {
    zone: {
      data: [],
      total: 0,
    },
    selectedZone: [],
    location: '',
    isZoneSelected: false,
  },
})
@Injectable()
export class ZoneState {
  private zoneService = inject(ZoneService);
  private store = inject(Store);

  @Selector()
  static zone(state: ZoneStateModel) {
    return state.zone;
  }

  @Selector()
  static location(state: ZoneStateModel) {
    return state.location;
  }

  @Selector()
  static selectedZone(state: ZoneStateModel) {
    return state.selectedZone;
  }

  @Selector()
  static isZoneSelected(state: ZoneStateModel) {
    return state.isZoneSelected;
  }

  @Action(GetZoneAction)
  getZone(ctx: StateContext<ZoneStateModel>, action: GetZoneAction) {
    return this.zoneService.getZone(action.payload).pipe(
      tap({
        next: result => {
          ctx.patchState({
            selectedZone: result.length
              ? result.map((item: { id: number; name: string }) => item.id)
              : [],
            isZoneSelected: true,
          });
          this.store.dispatch(new ClearCartAction());
        },
        error: err => {
          throw new Error(err?.error?.message);
        },
      }),
    );
  }

  @Action(SaveLocationAction)
  saveAddress(ctx: StateContext<ZoneStateModel>, action: SaveLocationAction) {
    ctx.patchState({
      location: action.location,
    });
  }

  @Action(ClearZoneAction)
  clearZone(ctx: StateContext<ZoneStateModel>) {
    ctx.patchState({
      location: '',
      selectedZone: [],
      isZoneSelected: false,
    });
  }

  @Action(IsSelectedZoneAction)
  isZoneSelected(ctx: StateContext<ZoneStateModel>) {
    ctx.patchState({
      // isZoneSelected: !state.selectedZone.length
    });
  }
}
