import { computed, inject } from '@angular/core';
import {
  deduplicateAddressees,
  deduplicateBranches,
} from '@isa/crm/data-access';
import { DisplayOrdersResource } from '@isa/oms/data-access';
import {
  hasOrderTypeFeature,
  OrderTypeFeature,
} from '@isa/checkout/data-access';
import {
  patchState,
  signalStore,
  withComputed,
  withMethods,
  withProps,
  withState,
} from '@ngrx/signals';

type OrderConfiramtionState = {
  tabId: number | undefined;
  orderIds: number[] | undefined;
};

const initialState: OrderConfiramtionState = {
  tabId: undefined,
  orderIds: undefined,
};

export const OrderConfiramtionStore = signalStore(
  withState(initialState),
  withProps(() => ({
    _displayOrdersResource: inject(DisplayOrdersResource),
  })),
  withComputed((state) => ({
    orders: computed(() => {
      const orders = state._displayOrdersResource.orders();

      if (!orders || orders.length === 0) {
        return undefined;
      }

      return orders;
    }),
    loading: computed(() => state._displayOrdersResource.loading()),
    error: computed(() => state._displayOrdersResource.error()),
  })),
  withComputed((state) => ({
    payers: computed(() => {
      const orders = state.orders();
      if (!orders) {
        return undefined;
      }
      const buyers = orders.map((order) => order.buyer);
      return deduplicateAddressees(buyers);
    }),
    shippingAddresses: computed(() => {
      const orders = state.orders();
      if (!orders) {
        return undefined;
      }
      const addresses = orders.map((order) => order.shippingAddress);
      return deduplicateAddressees(addresses);
    }),
    targetBranches: computed(() => {
      const orders = state.orders();
      if (!orders) {
        return undefined;
      }
      const branches = orders.map((order) => order.targetBranch);
      return deduplicateBranches(branches);
    }),
    hasDeliveryOrderTypeFeature: computed(() => {
      const orders = state.orders();
      if (!orders || orders.length === 0) {
        return false;
      }
      return orders.some((order) => {
        return hasOrderTypeFeature(order.features, [
          OrderTypeFeature.Delivery,
          OrderTypeFeature.DigitalShipping,
          OrderTypeFeature.B2BShipping,
        ]);
      });
    }),
    hasTargetBranchFeature: computed(() => {
      const orders = state.orders();
      if (!orders || orders.length === 0) {
        return false;
      }
      return orders.some((order) => {
        return hasOrderTypeFeature(order.features, [
          OrderTypeFeature.InStore,
          OrderTypeFeature.Pickup,
        ]);
      });
    }),
  })),
  withMethods((store) => ({
    patch(partial: Partial<OrderConfiramtionState>) {
      patchState(store, partial);
    },
  })),
);
