import { Maybe } from '@/core';
import { PosInfoStore } from '@/domains/pos/store';
import { SharedGoodFormComponent } from '@/shared/components/good';
import { InnerPagesHeaderComponent } from '@/shared/components/innerPagesHeader/inner-pages-header.component';
import pageParamsUtils from '@/utils/page-params.utils';
import { Component, computed, inject, signal } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { finalize } from 'rxjs';
import { PosGoodsManagementRoutes } from '../constants';
import { IPosGoodsManagementResponse } from '../models';
import { PosOwnedGoodsService } from '../services/main.service';

@Component({
  selector: 'pos-good-update',
  templateUrl: './update.component.html',
  imports: [SharedGoodFormComponent, InnerPagesHeaderComponent],
})
export class PosGoodsUpdateComponent {
  private readonly route = inject(ActivatedRoute);
  private readonly router = inject(Router);
  private readonly store = inject(PosInfoStore);
  private readonly service = inject(PosOwnedGoodsService);

  loading = signal(true);
  item = signal<Maybe<IPosGoodsManagementResponse>>(null);

  pageParams = computed(() => pageParamsUtils(this.route));
  goodId = signal<string>(this.pageParams()['goodId']);

  readonly backRoute = PosGoodsManagementRoutes.goods.meta.pagePath!();

  preparedPageTitle = computed(() => `ویرایش ${this.item()?.name || ''}`);
  readonly guildId = computed(() => this.store.entity()?.guild.id || '');

  ngOnInit() {
    this.loading.set(true);
    this.service
      .get(this.goodId())
      .pipe(
        finalize(() => {
          this.loading.set(false);
        })
      )
      .subscribe((res) => {
        this.item.set(res);
      });
  }

  onSubmit() {
    this.onPrev();
  }

  onPrev() {
    this.router.navigateByUrl(PosGoodsManagementRoutes.goods.meta.pagePath!());
  }

  updateFn = (payload: FormData) => {
    return this.service.update(this.goodId(), payload);
  };
}
