<script setup>
import Sidebar from "./components/Sidebar.vue";
import Tabs from "./components/Tabs.vue";
import { computed, onMounted, watch, ref, provide, getCurrentInstance } from "vue";
import { useFormBuilderStore } from "./store";
import { onClickOutside } from "@vueuse/core";
import { NMessageProvider, NDialogProvider } from 'naive-ui';
import { registerGlobalComponents } from "./globals";

// Register control components globally
const app = getCurrentInstance()?.appContext.app;
if (app) {
  registerGlobalComponents(app);
}

// Props
const props = defineProps({
  fields: {
    type: Array,
    default: () => []
  },
  pagetype: {
    type: String,
    default: ""
  },
  pagetypeRecord: {
    type: Object,
    default: null
  },
  readOnly: {
    type: Boolean,
    default: false
  },
  isCustomizeForm: {
    type: Boolean,
    default: false
  }
});

// Emits
const emit = defineEmits(['update:fields', 'save', 'dirty-change']);

let store = useFormBuilderStore();

// Provide store to all children
provide('formBuilderStore', store);

let shouldRender = computed(() => {
  return Object.keys(store.form.layout).length !== 0 && 
         store.form.layout.tabs && 
         store.form.layout.tabs.length > 0;
});

let container = ref(null);
let dialogContainer = ref(null);
let messageContainer = ref(null);
let sidebarWidth = ref(300);
let isResizing = ref(false);
let startX = ref(0);
let startWidth = ref(300);

const minSidebarWidth = 260;
const maxSidebarWidth = 500;

onClickOutside(container, () => (store.form.selected_field = null), {
  ignore: [".combo-box-options", ".dropdown-options", ".n-popover"],
});

watch(
  () => store.form.layout,
  () => {
    store.dirty = true;
    emit('dirty-change', true);
  },
  { deep: true }
);

// Watch for dirty state changes
watch(
  () => store.dirty,
  (newVal) => {
    emit('dirty-change', newVal);
  }
);

// Initialize the store on mount
onMounted(() => {
  dialogContainer.value = document.body;
  messageContainer.value = document.body;
  
  store.initialize(props.fields, {
    pagetype: props.pagetype,
    pg: props.pagetypeRecord,
    readOnly: props.readOnly,
    isCustomizeForm: props.isCustomizeForm,
  });
});

// Watch for prop changes
watch(
  () => props.fields,
  (newFields) => {
    store.initialize(newFields, {
      pagetype: props.pagetype,
      pg: props.pagetypeRecord,
      readOnly: props.readOnly,
      isCustomizeForm: props.isCustomizeForm,
    });
  },
  { deep: true }
);

// Expose methods for parent components
function getFields() {
  return store.getUpdatedFields();
}

function validate() {
  const fields = store.getUpdatedFields();
  return store.validateFields(fields, false);
}

function save() {
  const errorMessage = validate();
  if (errorMessage) {
    return { success: false, message: errorMessage };
  }
  
  const fields = store.getUpdatedFields();
  emit('update:fields', fields);
  emit('save', fields);
  store.dirty = false;
  return { success: true, fields };
}

// Resize handle functions
function startResize(event) {
  event.preventDefault();
  event.stopPropagation();
  
  startX.value = event.clientX;
  startWidth.value = sidebarWidth.value;
  
  isResizing.value = true;
  document.body.style.cursor = 'col-resize';
  document.body.style.userSelect = 'none';
  
  document.addEventListener('mousemove', handleMouseMove);
  document.addEventListener('mouseup', stopResize);
}

function handleMouseMove(event) {
  if (!isResizing.value) return;
  
  const deltaX = startX.value - event.clientX;
  const newWidth = startWidth.value + deltaX;
  
  if (newWidth >= minSidebarWidth && newWidth <= maxSidebarWidth) {
    sidebarWidth.value = newWidth;
  }
}

function stopResize() {
  isResizing.value = false;
  document.body.style.cursor = '';
  document.body.style.userSelect = '';
  
  document.removeEventListener('mousemove', handleMouseMove);
  document.removeEventListener('mouseup', stopResize);
}

defineExpose({
  getFields,
  validate,
  save,
  store
});
</script>

<template>
  <n-message-provider :to="messageContainer">
    <n-dialog-provider :to="dialogContainer">
      <div
        v-if="shouldRender"
        ref="container"
        class="form-builder-container"
        :class="{ resizing: isResizing }"
        @click="store.form.selected_field = null"
      >
        <div class="form-container">
          <div class="form-main" :class="[store.preview ? 'preview' : '']">
            <Tabs />
          </div>
        </div>
        <div class="resize-handle" @mousedown="startResize"></div>
        <div class="form-controls" @click.stop>
          <div class="form-sidebar" :style="{ width: sidebarWidth + 'px' }">
            <Sidebar />
          </div>
        </div>
      </div>
      <div v-else class="form-builder-loading">
        <span>Loading form builder...</span>
      </div>
      <div id="autocomplete-area" />
    </n-dialog-provider>
  </n-message-provider>
</template>

<style lang="scss" scoped>
.form-builder-loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
  color: var(--text-muted, #6c757d);
}

.form-builder-container {
  display: flex;
  min-height: 600px;
  height: 100%;
  overflow: hidden;

  &.resizing {
    user-select: none;
    cursor: col-resize;
  }

  .form-controls {
    position: relative;
    flex-shrink: 0;
  }

  .form-container {
    flex: 1;
    background-color: #f8f9fa;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }

  .form-sidebar {
    border-left: 1px solid #e5e7eb;
    border-radius: 8px;
    background-color: #fff;
    height: 100%;
    overflow-y: auto;
    overflow-x: hidden;
  }

  .form-main {
    border-radius: 8px;
    border: 1px solid #e5e7eb;
    background-color: #fff;
    margin: 5px;
    flex: 1;
    overflow-y: auto;
    overflow-x: hidden;
    display: flex;
    flex-direction: column;
  }

  .resize-handle {
    width: 4px;
    background-color: transparent;
    cursor: col-resize;
    position: relative;
    transition: all 0.2s ease;
    flex-shrink: 0;
    z-index: 10;
    
    &:hover {
      background-color: rgba(59, 130, 246, 0.1);
    }
    
    &::after {
      content: '';
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 1px;
      height: 24px;
      background: linear-gradient(180deg, 
        rgba(156, 163, 175, 0.3) 0%, 
        rgba(156, 163, 175, 0.6) 50%, 
        rgba(156, 163, 175, 0.3) 100%);
      border-radius: 0.5px;
      transition: all 0.2s ease;
    }
    
    &:hover::after {
      background: linear-gradient(180deg, 
        rgba(59, 130, 246, 0.4) 0%, 
        rgba(59, 130, 246, 0.8) 50%, 
        rgba(59, 130, 246, 0.4) 100%);
      width: 2px;
      height: 32px;
    }
    
    &:active {
      background-color: rgba(59, 130, 246, 0.15);
    }
  }

  .form-sidebar,
  .form-main {
    :deep(.section-columns.has-one-column .field) {
      input.form-control,
      .signature-field {
        width: calc(50% - 19px);
      }

      .select-input {
        width: calc(50% - 19px);

        input.form-control {
          width: 100%;
        }
      }
    }

    :deep(.column-container .field.sortable-chosen) {
      background-color: #f3f4f6;
      border-radius: 4px;
      border: 1px solid transparent;
      padding: 0.3rem;
      font-size: 14px;
      cursor: pointer;

      &:not(.hovered) {
        position: relative;
        background-color: transparent;
        height: 60px;

        .drop-it-here {
          display: flex;
          justify-content: center;

          &::after {
            content: "Drop it here";
            top: 31%;
            position: absolute;
            padding: 2px 10px;
            color: #374151;
            background-color: #9ca3af;
            border-radius: 9999px;
            z-index: 1;
          }
          &::before {
            content: "";
            top: 47%;
            position: absolute;
            width: 97%;
            height: 4px;
            background-color: #9ca3af;
            border-radius: 9999px;
          }
        }
      }

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

    :deep(.field) {
      .label {
        margin-bottom: 0.3rem;
      }

      .editable {
        input,
        textarea,
        select,
        .ace_editor,
        .ace_gutter,
        .ace_content,
        .signature-field,
        .missing-image,
        .ql-editor {
          background-color: #fff;
          cursor: pointer;
        }

        .input-text {
          background-color: inherit;
        }
      }

      .description,
      .time-zone {
        font-size: 12px;
        color: #6b7280;
      }
    }

    :deep([data-is-user-generated="1"]) {
      background-color: #fef3c7;
    }
  }

  :deep(.preview) {
    .tab,
    .column,
    .field {
      background-color: #fff;
    }

    .column,
    .field {
      border: none;
      padding: 0;
    }

    .form-section {
      padding: 5px;

      .section-header {
        &.has-label {
          padding: 10px 15px;
          margin-bottom: 8px;
        }

        &.collapsed {
          margin-bottom: 0;
        }
      }

      .section-description {
        padding-left: 15px;
      }

      .section-columns {
        margin-top: 8px;

        &.has-one-column .field {
          input.form-control,
          .signature-field {
            width: calc(50% - 15px);
          }

          .select-input {
            width: calc(50% - 15px);

            input.form-control {
              width: 100%;
            }
          }
        }

        .section-columns-container {
          .column {
            padding-left: 15px;
            padding-right: 15px;
            margin: 0;

            .column-header {
              padding-left: 0;
            }

            .column-description {
              margin-left: 0;
            }

            .field {
              margin: 0;
              margin-bottom: 1rem;
              .field-controls {
                margin-bottom: 5px;
              }
            }

            .add-new-field-btn {
              display: none;
            }
          }
        }
      }
    }

    .selected,
    .hovered {
      border-color: transparent;
    }

    input,
    textarea,
    select,
    .ace_editor,
    .ace_gutter,
    .ace_content,
    .signature-field,
    .missing-image,
    .ql-editor {
      background-color: #f9fafb !important;
    }

    input[type="checkbox"] {
      background-color: #fff !important;
    }
  }

  .form-main > :deep(div:first-child:not(.tab-header)) {
    max-height: calc(100vh - 175px);
  }
}
</style>
