<script setup>
import EditableInput from "./EditableInput.vue";
import { useFormBuilderStore } from "../store";
import { moveChildrenToParent, cloneField } from "../utils";
import { ref, computed, onMounted } from "vue";
import AddFieldButton from "./AddFieldButton.vue";
import { useMagicKeys, whenever } from "@vueuse/core";
import { Icon } from '@iconify/vue';
import { t } from '@/shared/i18n';

const props = defineProps(["column", "field"]);
const store = useFormBuilderStore();

const addFieldRef = ref(null);

// cmd/ctrl + shift + n to open the add field autocomplete
const { ctrl_shift_n, Backspace } = useMagicKeys();
whenever(ctrl_shift_n, (value) => {
  if (value && selected.value) {
    addFieldRef.value?.open();
  }
});

// delete/backspace to delete the field
whenever(Backspace, (value) => {
  if (value && selected.value && store.notUsingInput) {
    removeField();
  }
});

const labelInput = ref(null);
const hovered = ref(false);
const selected = computed(() => store.selected(props.field.df.name));
const component = computed(() => {
  return props.field.df.fieldtype.replaceAll(" ", "") + "Control";
});

function removeField() {
  if (store.isCustomizeForm && props.field.df.is_custom_field === 0) {
    alert(t("Cannot delete standard field. You can hide it if you want"));
    throw "cannot delete standard field";
  }
  let index = props.column.fields.indexOf(props.field);
  props.column.fields.splice(index, 1);
  store.form.selected_field = null;
}

function moveFieldsToColumn() {
  let currentSection = store.currentTab?.sections?.find((section) =>
    section.columns.find((column) => column === props.column)
  );
  if (currentSection) {
    moveChildrenToParent(props, "column", "field", currentSection, store.getDf);
  }
}

function duplicateField() {
  let duplicatedField = cloneField(props.field);

  if (store.isCustomizeForm) {
    duplicatedField.df.is_custom_field = 1;
  }

  if (duplicatedField.df.label) {
    duplicatedField.df.label = duplicatedField.df.label + " Copy";
  }
  duplicatedField.df.fieldname = "";
  duplicatedField.df.__islocal = 1;
  duplicatedField.df.__unsaved = 1;

  delete duplicatedField.df.creation;
  delete duplicatedField.df.modified;
  delete duplicatedField.df.modified_by;

  let index = props.column.fields.indexOf(props.field);
  props.column.fields.splice(index + 1, 0, duplicatedField);
  store.form.selected_field = duplicatedField.df;
}

onMounted(() => selected.value && labelInput.value?.focusOnLabel?.());
</script>

<template>
  <div
    :class="['field', selected ? 'selected' : hovered ? 'hovered' : '']"
    :title="field.df.fieldname"
    @click.stop="store.form.selected_field = field.df"
    @mouseover.stop="hovered = true"
    @mouseout.stop="hovered = false"
  >
    <component
      :is="component"
      :df="field.df"
      :data-fieldname="field.df.fieldname"
      :data-fieldtype="field.df.fieldtype"
    >
      <template #label>
        <div class="field-label">
          <EditableInput
            ref="labelInput"
            :text="field.df.label"
            :placeholder="t('Label')"
            :emptyLabel="`${t('No Label')} (${field.df.fieldtype})`"
            v-model="field.df.label"
          />
          <div class="reqd-asterisk" v-if="field.df.reqd">*</div>
          <div
            class="help-icon"
            v-if="field.df.documentation_url"
          >
            <Icon icon="mdi:help-circle-outline" class="icon-sm" />
          </div>
        </div>
      </template>
      <template #actions>
        <div class="field-actions" :hidden="store.readOnly">
          <AddFieldButton ref="addFieldRef" :column="column" :field="field">
            <Icon icon="mdi:plus" class="icon-sm" />
          </AddFieldButton>
          <button
            v-if="column.fields.indexOf(field)"
            class="btn btn-xs btn-icon"
            :title="t('Move the current field and the following fields to a new column')"
            @click="moveFieldsToColumn"
          >
            <Icon icon="mdi:arrow-right-box" class="icon-sm" />
          </button>
          <button
            class="btn btn-xs btn-icon"
            :title="t('Duplicate field')"
            @click.stop="duplicateField"
          >
            <Icon icon="mdi:content-copy" class="icon-sm" />
          </button>
          <button
            class="btn btn-xs btn-icon"
            :title="t('Remove field')"
            @click.stop="removeField"
          >
            <Icon icon="mdi:close" class="icon-sm" />
          </button>
        </div>
      </template>
    </component>
  </div>
</template>

<style lang="scss" scoped>
.field {
  text-align: left;
  width: 100%;
  background-color: #f3f4f6;
  border-radius: 4px;
  border: 1px solid transparent;
  padding: 0.3rem;
  font-size: 14px;

  &:not(:first-child) {
    margin-top: 0.4rem;
  }

  &.hovered,
  &.selected {
    border-color: #3b82f6;
    .btn.btn-icon {
      opacity: 1 !important;
    }
  }

  :deep(.form-control:read-only:focus) {
    box-shadow: none;
  }

  :deep(.field-controls) {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 0.3rem;

    .field-label {
      display: flex;
      align-items: center;
      .reqd-asterisk {
        margin-left: 3px;
        color: #ef4444;
      }
      .help-icon {
        margin-left: 3px;
        color: #6b7280;
        cursor: pointer;
      }
    }

    .field-actions {
      flex: none;
      display: flex;
      gap: 2px;

      .btn.btn-icon {
        opacity: 0;
        box-shadow: none;
        padding: 2px;
        border: none;
        background: transparent;
        cursor: pointer;

        &:hover {
          background-color: #fff;
        }
      }
    }
  }
}

.btn-filter-applied {
  background-color: #d1d5db !important;
  &:hover {
    background-color: #9ca3af !important;
  }
}

.icon-sm {
  width: 14px;
  height: 14px;
}
</style>
