import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { LabelValueItem } from '../types/services-types';
import cloneDeep from 'lodash/cloneDeep';
import { QDialog, QForm } from 'quasar';
import { noEmptyValueWithCustomMessageRule } from '@utils/field-validation/basic';

const defaultItem: LabelValueItem = { label: '', value: '' };
@Component({
  methods: {
    noEmptyValueWithCustomMessageRule,
  },
})
export default class ServicesBasicItemsList extends Vue {
  @Prop() headerLabel: string;
  @Prop() columnValueLabel: string;
  @Prop() columnLabelLabel: string;
  @Prop() buttonAddLabel: string;
  @Prop() validationLabel: string;
  @Prop() validationValueLabel: string;

  @Prop() items: LabelValueItem[];
  @Prop() editMode: boolean;

  list: LabelValueItem[] = [];
  showItemModal = false;
  currentItem: LabelValueItem = cloneDeep(defaultItem);
  editing = false;
  editingIndex: number | null = null;

  mounted(): void {
    this.list = cloneDeep(this.items) || [];
  }

  @Watch('list', { deep: true })
  onListChange(updated: LabelValueItem[]): void {
    this.$emit('update:items', updated);
  }

  private async addItemEntry(): Promise<void> {
    const form = this.$refs.form as QForm;

    const isValid = await form.validate();

    if (!isValid) return;

    this.list.push(this.currentItem);

    this.closeItemModal();
  }

  private editItemEntry(entry: LabelValueItem): void {
    this.editing = true;
    this.editingIndex = this.list.indexOf(entry);
    this.currentItem = cloneDeep(entry);
    this.showItemModal = true;
  }

  private applyItemEntryChanges(): void {
    if (typeof this.editingIndex === 'number') {
      this.list.splice(this.editingIndex, 1, this.currentItem);
    }

    this.editing = false;
    this.editingIndex = null;

    this.closeItemModal();
  }

  private deleteItemEntry(entry: LabelValueItem): void {
    this.list = this.list.filter(
      (listEntry) => entry.value !== listEntry.value
    );
  }

  private closeItemModal(): void {
    this.currentItem = cloneDeep(defaultItem);

    const modal = this.$refs.itemModal as QDialog;

    modal.hide();
  }

  accept() {
    console.log(this.editing);
    this.editing ? this.applyItemEntryChanges() : this.addItemEntry();
  }
}
