<template>
  <div class>
    <div class="prvi form-header">
      <h2 class="form-title">{{ title }}</h2>
      <button class="btn btn-secondary" @click="addField">+</button>
    </div>
    <span v-if="formDescription">{{ formDescription }}</span>
    <div class="form-builder">
      <div class="__form-content" :class="{ 'is-empty': localFields.length === 0 }">
        <div v-if="localFields.length === 0" class="empty-text">
          {{ empty }}
        </div>
        <div v-else class="field-list">
          <draggable :list="localFields" :animation="200">
            <div v-for="(field, index) in localFields" :key="field.id" class="field-wrapper mb-1">
              <div class="field-group">
                <div class="field-item">
                  <div class="field-icon-wrapper">
                    <i :class="['mdi', getFieldIcon(field.type)]" style="font-size: 24px;"></i>
                  </div>
                  <div class="field-label">{{ field.name }}</div>
                  <span class="field-arrow" @click="expandForm(index)" :class="{ rotated: field.expanded }">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path fill-rule="evenodd" clip-rule="evenodd" d="M6.96888 2.46936C7.03854 2.39952 7.12131 2.34411 7.21243 2.3063C7.30354 2.26849 7.40122 2.24902 7.49988 2.24902C7.59853 2.24902 7.69621 2.26849 7.78733 2.3063C7.87844 2.34411 7.96121 2.39952 8.03088 2.46936L17.0309 11.4694C17.1007 11.539 17.1561 11.6218 17.1939 11.7129C17.2318 11.804 17.2512 11.9017 17.2512 12.0004C17.2512 12.099 17.2318 12.1967 17.1939 12.2878C17.1561 12.3789 17.1007 12.4617 17.0309 12.5314L8.03088 21.5314C7.89005 21.6722 7.69904 21.7513 7.49988 21.7513C7.30071 21.7513 7.10971 21.6722 6.96888 21.5314C6.82805 21.3905 6.74893 21.1995 6.74893 21.0004C6.74893 20.8012 6.82805 20.6102 6.96888 20.4694L15.4394 12.0004L6.96888 3.53136C6.89903 3.4617 6.84362 3.37893 6.80581 3.28781C6.768 3.1967 6.74854 3.09902 6.74854 3.00036C6.74854 2.90171 6.768 2.80403 6.80581 2.71291C6.84362 2.6218 6.89903 2.53903 6.96888 2.46936Z" fill="black"/> </svg>
                  </span>
                </div>
                <div v-if="field.expanded" class="expanded-content">
                  <div class="btn-group" role="group" aria-label="Basic example">
                    <button type="button" class="btn btn-secondary" :class="{ active: activeTabs[field.id] === 'Detalii' }" @click="setTab(field.id, 'Detalii')">Detalii</button>
                    <button type="button" class="btn btn-secondary" :class="{ active: activeTabs[field.id] === 'Actiuni' }" @click="setTab(field.id, 'Actiuni')">Actiuni</button>
                    <button type="button" class="btn btn-secondary" :class="{ active: activeTabs[field.id] === 'Optiuni' }" @click="setTab(field.id, 'Optiuni')">Optiuni</button>
                  </div>

                  <div class="form-fields" v-if="activeTabs[field.id] === 'Detalii'">
                    <input type="text" v-model="editCache[field.id].editableData.name" class="form-input" placeholder="Titlu câmp" />
                    <select class="form-control" v-model="editCache[field.id].editableData.type" @change="onTypeChange(field.id, $event)">
                      <option v-for="field in fieldList" :key="field.id" :value="field.id">{{ field.title }}</option>
                    </select>
                    <textarea v-model="editCache[field.id].editableData.description" class="form-input" placeholder="Descriere"></textarea>
                    <colorPicker
                      v-if="isSelectType(field.id)"
                      v-model="editCache[field.id].editableData.values"
                      :disableColors="!allowColors"
                      placeholder="Add option.."
                    />
                  </div>
                  <div class='form-action' v-if="activeTabs[field.id] === 'Actiuni'">
                   <Actions
                      v-model="editCache[field.id].editableData.actions"
                      :list="availableActions"
                      :class_select="class_select"
                      @current-selection-changed="handleCurrentSelectionChanged"> 
                    </Actions>
                  </div>
                  <div class="form-fields-options" v-if="activeTabs[field.id] === 'Optiuni'">
                    <div v-for="optionId in getCurrentFieldOptionList(editCache[field.id].editableData.type)" :key="optionId">
                      <div v-if="getFieldOptionData(optionId).type === 'text'">
                        <label class="form-label">{{ getFieldOptionData(optionId).title }}</label>
                        <div class="input-with-description">
                          <input
                            type="text"
                            class="form-input"
                            :placeholder="getFieldOptionData(optionId).placeholder"
                            v-model="editCache[field.id].editableOptions[optionId]"
                          />
                          <span v-if="getFieldOptionData(optionId).description" class="option-description">
                            {{ getFieldOptionData(optionId).description }}
                          </span>
                        </div>
                      </div>
                      <div v-if="getFieldOptionData(optionId).type === 'numeric'">
                        <label class="form-label">{{ getFieldOptionData(optionId).title }}</label>
                        <div class="input-with-description">
                          <input
                            type="number"
                            class="form-input"
                            :placeholder="getFieldOptionData(optionId).placeholder"
                            v-model="editCache[field.id].editableOptions[optionId]"
                          />
                          <span v-if="getFieldOptionData(optionId).description" class="option-description">
                            {{ getFieldOptionData(optionId).description }}
                          </span>
                        </div>
                      </div>
                      <div v-if="getFieldOptionData(optionId).type === 'textarea'">
                        <label class="form-label">{{ getFieldOptionData(optionId).title }}</label>
                        <div class="input-with-description">
                          <textarea
                            class="form-input"
                            :placeholder="getFieldOptionData(optionId).placeholder"
                            v-model="editCache[field.id].editableOptions[optionId]"
                          />
                          <span v-if="getFieldOptionData(optionId).description" class="option-description">
                            {{ getFieldOptionData(optionId).description }}
                          </span>
                        </div>
                      </div>
                      <div v-if="getFieldOptionData(optionId).type === 'boolean'" class="form-fields">
                        <div class="input-with-description">
                          <div class="switch-line">
                            <input-checkbox
                              :caption="getFieldOptionData(optionId).title"
                              :captionAside="true"
                              v-model="editCache[field.id].editableOptions[optionId]"
                            />
                          </div>
                          <span
                            v-if="getFieldOptionData(optionId).description"
                            class="option-description"
                          >
                            {{ getFieldOptionData(optionId).description }}
                          </span>
                        </div>
                      </div>
                      <div v-if="getFieldOptionData(optionId).type === 'select'">
                        <label class="form-label">{{ getFieldOptionData(optionId).title }}</label>
                        <div class="input-with-description">
                          <select
                            class="form-input"
                            v-model="editCache[field.id].editableOptions[optionId]"
                          >
                            <option
                              v-for="opt in getFieldOptionData(optionId).options"
                              :key="opt.id"
                              :value="opt.id"
                            >
                              {{ opt.title }}
                            </option>
                          </select>
                          <span v-if="getFieldOptionData(optionId).description" class="option-description">
                            {{ getFieldOptionData(optionId).description }}
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="form-buttons">
                    <button class="btn btn-secondary" @click="saveChanges(index)">Salveaza</button>
                    <button class="btn btn-danger" @click="deleteItem(index)">Sterge</button>
                  </div>
                </div>
              </div>
            </div>
          </draggable>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { inputCheckbox } from '@/index';
import colorPicker from './ColorPickerList.vue';
import Actions from '../basic/Actions.vue';
import { fieldOptions, fieldList } from '@/types';
import draggable from 'vuedraggable';
import { generateId } from '@/tools/util';

const fieldIconMapping = {
  'title': 'mdi-format-title',
  'paragraph': 'mdi-format-paragraph',
  'separator': 'mdi-minus',
  'text': 'mdi-form-textbox',
  'textarea': 'mdi-form-textarea',
  'attachment': 'mdi-file-image-outline',
  'checkbox': 'mdi-checkbox-marked-outline',
  'single_select': 'mdi-form-dropdown',
  'multiple_select': 'mdi-form-select',
  'numeric': 'mdi-numeric',
  'percent': 'mdi-percent-outline',
  'date': 'mdi-calendar-outline',
  'color': 'mdi-palette-outline',
  'url': 'mdi-link-variant',
  'password': 'mdi-lock-outline',
  'email': 'mdi-email-outline'
};

export default {
    components:{
      inputCheckbox,
      colorPicker,
      Actions,
      draggable
    },
    props: {
      value: {
        type: Array,
        default: () => []
      },
      title: {
        type: String,
      },
      empty: {
        type: String,
      },
      newFieldLabel: {
        type: String,
        default: 'Camp nou %d',
      },
      allowColors: {
        type: Boolean,
        default: true,
      },
      formDescription: {
        type: String,
        default: ''
      },
      availableActions: {
        type: Array,
        default: () => [
          {
            key: 'setare_valoare_initiala',
            title: 'Setează valoare inițială',
            type: 'text',
            placeholder: 'Formula',
            helperFields: [
              {
                key: 'sursa',
                type: 'select',
                options: [
                  { name: 'Selectează sursa', value: undefined },
                  { value: 'asset', name: 'Asset' },
                  { value: 'proces', name: 'Proces' }
                ],
                placeholder: 'Sursa'
              },
              {
                key: 'camp',
                type: 'text',
                placeholder: 'Câmp'
              }
            ]
          },
          {
            key: 'setare_valoare_finala',
            title: 'Setează valoare finală',
            type: 'text'
          },
          {
            key: 'suprascrie_valoare_initiala',
            title: 'Valoarea finală o va suprascrie pe cea inițială',
            type: 'boolean'
          }
        ]
      },
      class_select: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        fieldList,
        fieldOptions,
        activeTabs: {},
        editCache: {},
        fieldsData: [],
      };
    },
    mounted() {
      console.log('Formular mounted', fieldOptions, fieldList);
      this.fieldsData = this.value.map(this.normalizeField);
      console.log('Formular mounted123', this.fieldsData);
    },
    computed: {
      localFields: {
        get() {
          return this.value;
        },
        set(val) {
          this.$emit("input", val);
        }
      },
      isSelectType() {
        return (fieldId) => {
          const cache = this.editCache[fieldId];
          return cache && cache.editableData && 
            (cache.editableData.type === 'single_select' || 
             cache.editableData.type === 'multiple_select');
        };
      }
    },
    watch: {
      value: {
        handler(newVal) {
          this.fieldsData = newVal.map(this.normalizeField);
        },
        deep: true
      },
      'editCache': {
        handler(newEditCache) {
          Object.keys(newEditCache).forEach(fieldId => {
            const cache = newEditCache[fieldId];
            
            if (cache && cache.editableData) {
              const currentType = cache.editableData.type;
              
              if ((currentType === 'single_select' || currentType === 'multiple_select')) {
                if (!cache.editableData.values || cache.editableData.values.length === 0) {
                  this.$set(cache.editableData, 'values', [
                    { id: this.generateId(), title: "option 1", color: "#3b82f6" },
                  ]);
                }
              }
            }
          });
        },
        deep: true
      }
    },
    methods: {
      generateId,
      addField() {
        const nextIndex = this.fieldsData.length + 1;
        const type = 'text'; 
        const relevantOptionIds = this.getOptionsList(type);
        const filteredOptions = fieldOptions.filter(opt => relevantOptionIds.includes(opt.id));

        const newField = {
          id: this.generateId(),
          name: this.newFieldLabel.replace("%d", nextIndex),
          expanded: false,
          type: type,
          description: '',
          options: filteredOptions,
          actions: [],
        };

        if (type === 'single_select' || type === 'multiple_select') {
          newField.values = [
            { id: this.generateId(), title: "option 1", color: "#ff0000" },
          ];  
        }

        this.fieldsData = [...this.fieldsData, newField];
        this.$emit('input', this.fieldsData);
      },
      expandForm(index) {
        const updatedFields = [...this.fieldsData];
        const field = updatedFields[index];
        field.expanded = !field.expanded;
        if (field.expanded) {
          const editableData = { 
            name: field.name, 
            type: field.type, 
            description: field.description,
            values: (field.values || []).map(opt => ({
              id: opt.id || this.generateId(),   
              title: opt.title,
              color: opt.color || '#000000'
            })),
            actions: field.actions || [],
          };

          const relevantOptionIds = this.getOptionsList(field.type);
          const editableOptions = {};
            relevantOptionIds.forEach(optionId => {
            const existingOption = field.options.find(opt => opt.id === optionId);
            let value = existingOption ? existingOption.value : undefined;
            
            if (value === undefined || value === null) {
              const fieldOption = this.fieldOptions.find(fo => fo.id === optionId);
              if (fieldOption) {
                if (fieldOption.type === 'select') {
                  value = fieldOption.default || (fieldOption.options && fieldOption.options.length > 0 ? fieldOption.options[0].id : null);
                } else if (fieldOption.type === 'boolean') {
                  value = fieldOption.default || false;
                } else {
                  value = fieldOption.default || '';
                }
              }
            }
            
            editableOptions[optionId] = value;
          });

          this.$set(this.editCache, field.id, {
            editableData,
            editableOptions
          });
          this.$set(this.activeTabs, field.id, 'Detalii');
        } else {
          this.$delete(this.editCache, field.id);
          this.$delete(this.activeTabs, field.id);
        }
        this.fieldsData = updatedFields;
        this.$emit('input', this.fieldsData);
      },
      deleteItem(index) {
        const updatedFields = [...this.fieldsData];
        updatedFields.splice(index, 1); 
        this.fieldsData = updatedFields; 
        this.$emit('input', this.fieldsData);
      },
      saveChanges(index) {
        const updatedFields = [...this.fieldsData];
        const field = updatedFields[index];
        const cache = this.editCache[field.id];
        
        if (cache && cache.editableData) {
          const newOptions = this.getCurrentFieldOptionList(cache.editableData.type).map(optionId => {
            const optionData = this.fieldOptions.find(fo => fo.id === optionId);
            return {
              id: optionId,
              type: optionData.type,
              value: cache.editableOptions[optionId] !== undefined ? cache.editableOptions[optionId] : (optionData.default || '')
            };
          });

          const newType = cache.editableData.type;
          
          field.name = cache.editableData.name;
          field.type = newType;
          field.description = cache.editableData.description;
          field.actions = cache.editableData.actions;
          field.options = newOptions;

          if (newType === 'single_select' || newType === 'multiple_select') {
            if (cache.editableData.values && cache.editableData.values.length > 0) {
              field.values = cache.editableData.values.map(opt => ({
                id: opt.id || this.generateId(),
                title: opt.title,
                color: opt.color || '#000000'
              }));
            } else {
              field.values = [
                { id: this.generateId(), title: "option 1", color: "#3b82f6" }
              ];
            } 
          } else {
            delete field.values;
          }
        }
        
        field.expanded = false;
        this.$delete(this.editCache, field.id);
        this.$delete(this.activeTabs, field.id);
        this.fieldsData = updatedFields;
        this.$emit('input', this.fieldsData);
      },
      setTab(fieldId, tab) {
        this.$set(this.activeTabs, fieldId, tab);
      },
      getOptionValue(field, optionId) {
        const options = field.options;
        let opt = null;
        if (options && Array.isArray(options)) {
          opt = options.find(function(opt) {
            return opt.id === optionId;
          });
        }
        if (opt) {
          return opt.value;
        } else {
          return optionId === 'style' ? '' : false;
        }
      },
      updateOption(field, optionId, newValue) {
        const cache = this.editCache[field.id];
        if (!cache) return;

        const options = cache.editableOptions;
        if (options && Array.isArray(options)) {
          const opt = options.find(opt => opt.id === optionId);
          if (opt) {
            opt.value = newValue;
          }
        }
      },
      normalizeField(field){
        const type = field.type || 'text';
        const relevantOptionIds = this.getOptionsList(type);
        
        // Initialize options with default values if not present
        const normalizedOptions = relevantOptionIds.map(optionId => {
          const existingOption = field.options && field.options.find(opt => opt.id === optionId);
          const fieldOption = fieldOptions.find(fo => fo.id === optionId);
          
          return {
            id: optionId,
            type: fieldOption.type,
            value: existingOption ? existingOption.value : (fieldOption.default || (fieldOption.type === 'boolean' ? false : ''))
          };
        });

        const normalizedField = {
          id: field.id || this.generateId(),
          name: field.name || 'Camp nou',
          expanded: false,
          description: '',
          type: type,
          options: normalizedOptions,
          actions: [],
          ...field,
        };

        if (type === 'single_select' || type === 'multiple_select') {
          if (!normalizedField.values) {
            normalizedField.values = [
              { id: this.generateId(), title: "option 1", color: "#ff0000" }
            ];
          }
        } else {
          delete normalizedField.values;
        }

        return normalizedField;
      },
      getOptionsList(fieldId) {
        const field = this.fieldList.find(f => f.id === fieldId);
        return field.fieldOptionList;
      },
      getFieldOptionData(fieldId) {
        return this.fieldOptions.find(o => o.id === fieldId);
      },
      getCurrentFieldOptionList(fieldType) {
        const fieldDef = this.fieldList.find(f => f.id === fieldType);
        return fieldDef ? fieldDef.fieldOptionList : [];
      },
      onTypeChange(fieldId, event) {
        const newType = event.target.value;
        this.resetOptionsToDefaults(fieldId, newType);
      },
      resetOptionsToDefaults(fieldId, newType) {
        const cache = this.editCache[fieldId];
        if (!cache) return;
        
        const relevantOptionIds = this.getOptionsList(newType);
        const newEditableOptions = {};
        
        relevantOptionIds.forEach(optionId => {
          const fieldOption = this.fieldOptions.find(fo => fo.id === optionId);
          if (fieldOption) {
            if (fieldOption.type === 'boolean') {
              newEditableOptions[optionId] = fieldOption.default || false;
            } else if (fieldOption.type === 'select') {
              newEditableOptions[optionId] = fieldOption.default || (fieldOption.options && fieldOption.options.length > 0 ? fieldOption.options[0].id : null);
            } else {
              newEditableOptions[optionId] = fieldOption.default || '';
            }
          }
        });
        
        this.$set(cache, 'editableOptions', newEditableOptions);
        
        // Also reset values for select types
        if (newType === 'single_select' || newType === 'multiple_select') {
          if (!cache.editableData.values || cache.editableData.values.length === 0) {
            this.$set(cache.editableData, 'values', [
              { id: this.generateId(), title: "option 1", color: "#3b82f6" }
            ]);
          }
        }
      },
      handleCurrentSelectionChanged(event) {
        this.$emit('current-selection-changed', event);
      },
      getFieldIcon(type) {
        return fieldIconMapping[type] || 'mdi-form-textbox';
      }
    },
}
</script>

<style lang="scss" scoped>
// Variables
$border-radius: 6px;
$border-radius-small: 5px;
$spacing-xs: 4px;
$spacing-sm: 8px;
$spacing-md: 10px;
$spacing-lg: 25px;
$field-height: 50px;
$padding-horizontal: 12px;
$font-size-base: 14px;
$font-weight-normal: 400;
$font-weight-medium: 500;

// Colors
$color-white: white;
$color-light-gray: lightgray;
$color-black: black;
$color-gray: #888;
$color-border: #ccc;

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: $spacing-md;
  width: 100%;
}

.form-title {
  font-weight: $font-weight-normal;
}

.form-builder {
  background-color: $color-white;
  border-radius: $border-radius-small;
}

.form-content {
  width: 100%;
  height: 100%;
  
  &.is-empty {
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: $color-light-gray;
  }
}

.empty-text {
  color: $color-black;
  text-align: center;
}

.field-list {
  display: flex;
  flex-direction: column;
  gap: $spacing-xs;
  width: 100%;
}

.field-group {
  background-color: $color-light-gray;
  border-radius: $border-radius;
  overflow: hidden;
}

.field-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: $field-height;
  padding: 0 $padding-horizontal;
  cursor: grab;
}

.field-icon-wrapper {
  position: relative;
  width: 20px;
  height: 20px;
  
  i {
    position: absolute;
  }
}

.field-arrow {
  cursor: pointer;
  
  &.rotated {
    transform: rotate(90deg);
  }
}

.expanded-content {
  background-color: $color-light-gray;
  padding: $spacing-md;
}

.form-fields {
  padding-top: 5px;
  display: flex;
  flex-direction: column;
  gap: $spacing-sm;
}

.form-input {
  padding: $spacing-sm;
  border-radius: $border-radius;
  border: 1px solid $color-border;
  font-size: $font-size-base;
}

.form-buttons {
  margin-top: $spacing-md;
  display: flex;
  justify-content: flex-end;
  gap: 5px;
}

.form-label {
  font-weight: $font-weight-medium;
  margin-bottom: 1px;
}

textarea.form-input {
  min-height: 150px;
}

.form-action {
  margin-top: $spacing-xs;
}

.form-group.custom-switch.custom-switch-aside {
  padding: 0 !important;
  margin-bottom: 0 !important;
}

.input-with-description {
  display: flex;
  flex-direction: column;
  gap: 0;
  
  .option-description {
    margin-left: 0;
    color: $color-gray;
  }
  
  label {
    margin-bottom: 0 !important;
    padding-bottom: 0 !important;
  }
  
  .option-description {
    margin-top: 0 !important;
    padding-top: 0 !important;
    margin-bottom: 0 !important;
  }
}

.form-fields-options {
  display: flex;
  flex-direction: column;
  gap: $spacing-lg;
  padding-top: $spacing-md;
}
</style>
