import { Component, OnInit, OnDestroy } from '@angular/core';
import { Breadcrumb } from '../../../../core/models/breadcrumb.model';
import { AddBreadcrumb } from '../../../../core/store/actions/breadcrumb.actions';
import { ChangeCurrentRoute } from '../../../../core/store/actions/process.actions';
import { Store, Select } from '@ngxs/store';
import { Router, ActivatedRoute } from '@angular/router';
import { User, Address } from '../../../../core/models/user.model';
import { Observable, Subject } from 'rxjs';
import { CheckboxOption } from '@libs/ui';
import { takeUntil, map } from 'rxjs/operators';
import {
  SetActiveUser,
  SetUserDetails,
  SetDefaultInvoiceAddress,
  AddNewShippingAddress,
  AddNewInvoiceAddress,
  SetLastCreatedCustomerId,
} from '../../../../core/store/actions/customer.actions';
import { SharedSelectors } from '../../../../core/store/selectors/shared.selectors';
import { EditCustomerData } from '../../../../core/models/edit-customer.model';
import { ProcessSelectors } from '../../../../core/store/selectors/process.selectors';
import { isNullOrUndefined } from 'util';
import { query } from '@angular/animations';

@Component({
  selector: 'app-billing-address-dashboard',
  templateUrl: './customer-billing-address-dashboard.component.html',
  styleUrls: ['./customer-billing-address-dashboard.component.scss'],
})
export class CustomerBillingAddressDashboardComponent implements OnInit, OnDestroy {
  @Select(SharedSelectors.getCustomerEditData) customerEditData$: Observable<EditCustomerData>;
  destroy$ = new Subject();
  customer: User;
  invoiceAddresses: Address[] = [];
  selected;
  isCommingFromCart = false;
  notEditable = false;

  confirmCheckbox: CheckboxOption = {
    value: 'Rechnungsadresse entspricht der Lieferadresse',
    selected: false,
  };

  constructor(private store: Store, private router: Router, private route: ActivatedRoute) {}

  ngOnInit(): void {
    this.customerEditData$.pipe(takeUntil(this.destroy$)).subscribe((data: EditCustomerData) => {
      if (data && data.customer) {
        this.customer = data.customer;
        this.invoiceAddresses = data.customer.poossible_invoice_addresses;
        this.selected = data.customer.invoice_address;
      }
    });

    this.route.queryParams.pipe(takeUntil(this.destroy$)).subscribe((queryParams) => {
      if (queryParams && queryParams['cart']) {
        this.isCommingFromCart = true;
      }
      if (queryParams && queryParams['notEditable']) {
        this.notEditable = true;
      }
    });
  }

  select(invoiceAddress: Address) {
    this.selected = invoiceAddress;
    this.store.dispatch(new SetDefaultInvoiceAddress(this.customer.id, invoiceAddress));
  }

  addNew() {
    const queryParams = this.notEditable ? { notEditable: true } : undefined;
    const currentRoute = `/customer/edit/${this.customer.id}/billing/add`;
    const newBread: Breadcrumb = {
      name: 'Rechnungsadresse hinzufügen',
      path: currentRoute,
      queryParams,
    };
    this.store.dispatch(new AddBreadcrumb(newBread, this.isCommingFromCart ? 'shoppingCart' : 'customer'));
    this.store.dispatch(new ChangeCurrentRoute(currentRoute, false, queryParams));
    this.router.navigate([currentRoute], { queryParams: queryParams });
  }

  edit(id: number) {
    const queryParams = this.notEditable ? { notEditable: true } : undefined;
    const currentRoute = `/customer/edit/${this.customer.id}/billing/edit/${id}`;
    const newBread: Breadcrumb = {
      name: 'Rechnungsadresse ändern',
      path: currentRoute,
      queryParams,
    };
    this.store.dispatch(new AddBreadcrumb(newBread, this.isCommingFromCart ? 'shoppingCart' : 'customer'));
    this.store.dispatch(new ChangeCurrentRoute(currentRoute, false, queryParams));
    this.router.navigate([currentRoute], { queryParams: queryParams });
  }

  continue() {
    const updatedUser: User = { ...this.customer };
    updatedUser.invoice_address = this.selected;
    const process = this.store.selectSnapshot(ProcessSelectors.getCurrentProcess);

    const newBread: Breadcrumb = {
      name: 'Warenkorb',
      path: '/cart/review',
    };
    this.updateAddressessIfNeededAndPossible(updatedUser);
    this.store.dispatch(new SetUserDetails(updatedUser, false));
    this.store.dispatch(new AddBreadcrumb(newBread, 'shoppingCart'));
    this.store.dispatch(new ChangeCurrentRoute('/cart/review', true));
    this.store.dispatch(new SetLastCreatedCustomerId());

    if (!process.closeDirectlyTab) {
      this.store.dispatch(new SetActiveUser(updatedUser));
    }

    this.router.navigate(['/cart/review']);
  }

  private updateAddressessIfNeededAndPossible(customer: User) {
    if (!customer.delivery_addres && customer.invoice_address) {
      this.store.dispatch(new AddNewShippingAddress(customer.id, { ...customer.invoice_address, id: undefined }));
    }

    if (customer.delivery_addres && !customer.invoice_address) {
      this.store.dispatch(new AddNewInvoiceAddress(customer.id, { ...customer.delivery_addres, id: undefined }));
    }
  }

  ngOnDestroy() {
    this.destroy$.next();
  }

  getFullName(name: string, surname: string) {
    const _name = isNullOrUndefined(name) ? '' : name;
    const _surname = isNullOrUndefined(surname) ? '' : surname;
    return _name + ' ' + _surname;
  }
}
