<template>
  <q-page padding>
    <div class="text-h4 q-mb-md">
      Edit Form
    </div>

    <q-form
      v-if="!loading && form"
      @submit.prevent="updateForm"
      class="q-gutter-md"
    >
      <q-input
        outlined
        v-model="form.title"
        label="Form Title *"
        lazy-rules
        :rules="[ val => val && val.length > 0 || 'Please enter a title']"
      />

      <q-input
        outlined
        v-model="form.description"
        label="Form Description"
        type="textarea"
        autogrow
      />

      <q-separator class="q-my-lg" />

      <div class="text-h6 q-mb-sm">
        Categories & Fields
      </div>

      <div
        v-for="(category, catIndex) in form.categories"
        :key="category.id || catIndex"
        class="q-mb-lg q-pa-md bordered rounded-borders"
      >
        <div class="row items-center q-mb-sm">
          <q-input
            outlined
            dense
            v-model="category.name"
            :label="`Category ${catIndex + 1} Name *`"
            class="col q-mr-sm"
            lazy-rules
            :rules="[ val => val && val.length > 0 || 'Category name required']"
          />
          <q-btn
            flat
            round
            dense
            icon="delete"
            color="negative"
            @click="removeCategory(catIndex)"
            title="Remove Category"
          />
        </div>

        <div
          v-for="(field, fieldIndex) in category.fields"
          :key="field.id || fieldIndex"
          class="q-ml-md q-mb-sm"
        >
          <div class="row items-center q-gutter-sm">
            <q-input
              outlined
              dense
              v-model="field.label"
              label="Field Label *"
              class="col"
              lazy-rules
              :rules="[ val => val && val.length > 0 || 'Field label required']"
            />
            <q-select
              outlined
              dense
              v-model="field.type"
              :options="fieldTypes"
              label="Field Type *"
              class="col-auto"
              style="min-width: 150px;"
              lazy-rules
              :rules="[ val => !!val || 'Field type required']"
            />
            <q-btn
              flat
              round
              dense
              icon="delete"
              color="negative"
              @click="removeField(catIndex, fieldIndex)"
              title="Remove Field"
            />
          </div>
          <q-input
            v-model="field.description"
            label="Field Description (Optional)"
            outlined
            dense
            autogrow
            class="q-mt-xs q-mb-xl"
            hint="This description will appear below the field label on the form."
          />
        </div>
        <q-btn
          outline
          color="primary"
          label="Add Field"
          @click="addField(catIndex)"
          class="q-ml-md q-mt-sm"
        />
      </div>

      <q-btn
        outline
        color="secondary"
        label="Add Category"
        @click="addCategory"
      />

      <q-separator class="q-my-lg" />

      <div>
        <q-btn
          outline
          label="Update Form"
          type="submit"
          color="primary"
          :loading="submitting"
        />
        <q-btn
          outline
          label="Cancel"
          type="reset"
          color="warning"
          class="q-ml-sm"
          :to="{ name: 'formList' }"
        />
      </div>
    </q-form>
    <div v-else-if="loading">
      <q-spinner-dots
        color="primary"
        size="40px"
      />
      Loading form details...
    </div>
    <div
      v-else
      class="text-negative"
    >
      Failed to load form details.
    </div>
  </q-page>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'boot/axios';
import { useQuasar } from 'quasar';
import { useRouter, useRoute } from 'vue-router';

const props = defineProps({
  id: {
    type: String,
    required: true
  }
});

const $q = useQuasar();
const router = useRouter();
const route = useRoute(); // Use useRoute if needed, though id is from props

const form = ref(null); // Initialize as null
const loading = ref(true);
const fieldTypes = ref(['text', 'number', 'date', 'textarea', 'boolean']);
const submitting = ref(false);

async function fetchForm() 
{
  loading.value = true;
  try 
  {
    const response = await axios.get(`/api/forms/${props.id}`);
    // Ensure categories and fields exist, even if empty
    response.data.categories = response.data.categories || [];
    response.data.categories.forEach(cat => 
    {
      cat.fields = cat.fields || [];
    });
    form.value = response.data;
  }
  catch (error) 
  {
    console.error('Error fetching form details:', error);
    $q.notify({
      color: 'negative',
      position: 'top',
      message: 'Failed to load form details.',
      icon: 'report_problem'
    });
    form.value = null; // Indicate failure
  }
  finally 
  {
    loading.value = false;
  }
}

onMounted(fetchForm);

function addCategory() 
{
  if (!form.value.categories) 
  {
    form.value.categories = [];
  }
  form.value.categories.push({ name: `Category ${form.value.categories.length + 1}`, fields: [{ label: '', type: 'text', description: '' }] });
}

function removeCategory(index) 
{
  form.value.categories.splice(index, 1);
}

function addField(catIndex) 
{
  if (!form.value.categories[catIndex].fields) 
  {
    form.value.categories[catIndex].fields = [];
  }
  form.value.categories[catIndex].fields.push({ label: '', type: 'text', description: '' });
}

function removeField(catIndex, fieldIndex) 
{
  form.value.categories[catIndex].fields.splice(fieldIndex, 1);
}

async function updateForm() 
{
  submitting.value = true;
  try 
  {
    // Prepare payload, potentially removing temporary IDs if any were added client-side
    const payload = JSON.parse(JSON.stringify(form.value));
    // The backend PUT expects title, description, categories (with name, fields (with label, type, description))
    // We don't need to send the form ID in the body as it's in the URL

    await axios.put(`/api/forms/${props.id}`, payload);
    $q.notify({
      color: 'positive',
      position: 'top',
      message: `Form "${form.value.title}" updated successfully!`,
      icon: 'check_circle'
    });
    router.push({ name: 'formList' }); // Or maybe back to the form details/responses page
  }
  catch (error) 
  {
    console.error('Error updating form:', error);
    const message = error.response?.data?.error || 'Failed to update form. Please check the details and try again.';
    $q.notify({
      color: 'negative',
      position: 'top',
      message: message,
      icon: 'report_problem'
    });
  }
  finally 
  {
    submitting.value = false;
  }
}
</script>

<style scoped>
.bordered {
  border: 1px solid #ddd;
}
.rounded-borders {
  border-radius: 4px;
}
</style>
