<template>
  <div class="prvi form-builder-render">
    <div v-if="fields.length === 0" class="empty-form">
      {{ empty || 'Nu există câmpuri în formular.' }}
    </div>
    <div v-else class="form-content">
      <div v-for="field in fields" :key="field.id" class="form-field">
        <div class="field-content">
          <label v-if="field.type !== 'title'">{{ field.name }}</label>
          <component 
            :is="getFieldComponent(field.type)"
            v-if="field.type !== 'title'"
            :field="field"
            v-model="localValues[field.id]"
            :placeholder="getOptionValue(field, 'placeholder')"
            :caption="field.name"
            :description="field.description"
            :options="getFieldOptions(field)"
            :maxAttachments="parseInt(getOptionValue(field, 'file_count') || '1')"
            :maxSize="parseInt(getOptionValue(field, 'file_size') || '4') * 1024"
            :allowedExtensions="getExtensionsArray(field)"
            @input="updateMultipleSelectValue(field.id, $event)"
          />
          <component 
            v-else
            :is="getOptionValue(field, 'title_size') || 'h1'"
          >
            {{ field.name }}
          </component>
        </div>
      </div>
      <div v-if="showSubmitButton" class="form-buttons">
        <button class="btn btn-primary" @click="saveAllFields">{{ submitLabel }}</button>
      </div>
    </div>
  </div>
</template>

<script>
import { inputCheckbox } from '@/index'
import colorPicker from './ColorPickerList.vue'
import Select from '@/lib/basic/Select.vue'
import Attachment from '@/lib/files/Attachment.vue'
import MultipleSelect from '@/lib/basic/MultipleSelect.vue'

export default {
  
  components: {
    inputCheckbox,
    colorPicker,
    Select,
    Attachment,
    MultipleSelect
  },

  props: {
    fields: {
      type: Array,
      default: () => []
    },
    empty: {
      type: String,
      default: ''
    },
    value: {
      type: Array,
      default: () => []
    },
    submitLabel: {
      type: String,
      default: 'Salveaza'
    },
    showSubmitButton: {
      type: Boolean,
      default: true
    },
  },

  data() {
    return {
      localValues: {}
    }
  },

  created() {
    this.initializeValues()
  },

  watch: {
    fields: {
      handler: 'initializeValues',
      immediate: true
    }
  },

  methods: {
    getValue() {
      return Object.entries(this.localValues).map(([id, value]) => ({
        id,
        value
      }));
    },

    getOptionValue(field, optionId) {
      if (!field.options) return '';
      
      const option = field.options.find(opt => opt.id === optionId);
      return option ? option.value || option.title || '' : '';
    },

    getDefaultValue(fieldType, field) {
      const defaultFromOptions = this.getOptionValue(field, 'default_value');
      if (defaultFromOptions !== '') {
        return defaultFromOptions;
      }

      switch(fieldType) {
        case 'text':
        case 'textarea':
        case 'url':
        case 'email':
        case 'password':
          return '';
        case 'numeric':
          return null;
        case 'checkbox':
          return false;
        case 'single_select':
          return field.values && field.values.length > 0 ? field.values[0].id : '';
        default:
          return '';
      }
    },

    initializeValues() {
      const newValues = {};
      
      const existingValues = Array.isArray(this.value) ? 
        this.value.reduce((acc, item) => {
          acc[item.id] = item.value;
          return acc;
        }, {}) : {};

      this.fields.forEach(field => {
        if (field.type !== 'title') {
          newValues[field.id] = existingValues[field.id] !== undefined ? 
            existingValues[field.id] : 
            this.getDefaultValue(field.type, field);
        }
      });

      this.localValues = newValues;
    },

    saveAllFields() {
      this.$emit('input', this.getValue())
    },

    getFileSize(field) {
      return this.getOptionValue(field, 'file_size') || '4';
    },

    getFileCount(field) {
      return parseInt(this.getOptionValue(field, 'file_count') || '1');
    },

    getExtensionsArray(field) {
      const extensions = this.getOptionValue(field, 'extensions');
      if (!extensions) return [];
      
      return extensions.split(',').map(ext => ext.trim().toLowerCase().replace('.', ''));
    },

    updateMultipleSelectValue(fieldId, selectedOptions) {
      this.localValues[fieldId] = selectedOptions.map(opt => opt.itemKey);
    },

    getFieldComponent(fieldType) {
      switch(fieldType) {
        case 'text':
        case 'url':
        case 'password':
        case 'email':
          return 'input';
        case 'color':
          return 'input';
        case 'numeric':
        case 'percent':
          return 'input';
        case 'date':
          return 'input';
        case 'textarea':
          return 'textarea';
        case 'checkbox':
          return 'input-checkbox';
        case 'single_select':
          return 'Select';
        case 'attachment':
          return 'Attachment';
        case 'multiple_select':
          return 'MultipleSelect';
        default:
          return 'input';
      }
    },

    getFieldOptions(field) {
      if (field.type === 'single_select' || field.type === 'multiple_select') {
        return field.values.map(v => ({ name: v.title, value: v.id }));
      }
      return [];
    }
  }
}
</script>

<style scoped lang="scss">
.form-builder-render {
  width: 100%;
}

.form-content {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.field-content label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
}

.form-control {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.empty-form {
  padding: 20px;
  text-align: center;
  color: #666;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.form-textarea {
  min-height: 100px;
}
.form-group.custom-switch{
  padding: 0 !important;
}
.form-buttons {
  margin-top: 10px;
  display: flex;
  justify-content: flex-start;
  gap: 5px;
}

input[type="color"] {
  border: none;
  background: none;
  padding: 0;
  width: 50px;
  height: 30px;
  border-radius: 4px;
  cursor: pointer;
}

input[type="color"]::-webkit-color-swatch-wrapper {
  padding: 0;
  border: none;
  border-radius: 4px;
}

input[type="color"]::-webkit-color-swatch {
  border: none;
  border-radius: 4px;
}
</style>