<template>
  <q-page padding>
    <div class="q-mb-md row justify-between items-center">
      <div class="text-h4">
        Forms
      </div>
      <q-btn
        outline
        label="Create New Form"
        color="primary"
        :to="{ name: 'formCreate' }"
      />
    </div>

    <q-list
      bordered
      separator
      v-if="forms.length > 0"
    >
      <q-item
        v-for="form in forms"
        :key="form.id"
      >
        <q-item-section>
          <q-item-label>{{ form.title }}</q-item-label>
          <q-item-label caption>
            {{ form.description || 'No description' }}
          </q-item-label>
          <q-item-label caption>
            Created: {{ formatDate(form.createdAt) }}
          </q-item-label>
        </q-item-section>
        <q-item-section side>
          <div class="q-gutter-sm">
            <q-btn
              flat
              round
              dense
              icon="edit_note"
              color="info"
              :to="{ name: 'formFill', params: { id: form.id } }"
              title="Fill Form"
            />
            <q-btn
              flat
              round
              dense
              icon="visibility"
              color="secondary"
              :to="{ name: 'formResponses', params: { id: form.id } }"
              title="View Responses"
            />
            <q-btn
              flat
              round
              dense
              icon="edit"
              color="warning"
              :to="{ name: 'formEdit', params: { id: form.id } }"
              title="Edit Form"
            />
            <q-btn
              flat
              round
              dense
              icon="delete"
              color="negative"
              @click.stop="confirmDeleteForm(form.id)"
              title="Delete Form"
            />
          </div>
        </q-item-section>
      </q-item>
    </q-list>
    <q-banner
      v-else
      class="bg-info text-white"
    >
      <template #avatar>
        <q-icon
          name="info"
          color="white"
        />
      </template>
      No forms created yet. Click the button above to create your first form.
    </q-banner>

    <q-inner-loading :showing="loading">
      <q-spinner-gears
        size="50px"
        color="primary"
      />
    </q-inner-loading>
  </q-page>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { useQuasar } from 'quasar';

const $q = useQuasar();
const forms = ref([]);
const loading = ref(false);

async function fetchForms() 
{
  loading.value = true;
  try 
  {
    const response = await axios.get('/api/forms');
    forms.value = response.data;
  }
  catch (error) 
  {
    console.error('Error fetching forms:', error);
    $q.notify({
      color: 'negative',
      position: 'top',
      message: 'Failed to load forms. Please try again later.',
      icon: 'report_problem'
    });
  }
  finally 
  {
    loading.value = false;
  }
}

// Add function to handle delete confirmation
function confirmDeleteForm(id) 
{
  $q.dialog({
    title: 'Confirm Delete',
    message: 'Are you sure you want to delete this form and all its responses? This action cannot be undone.',
    cancel: true,
    persistent: true,
    ok: {
      label: 'Delete',
      color: 'negative',
      flat: false
    },
    cancel: {
      label: 'Cancel',
      flat: true
    }
  }).onOk(() => 
  {
    deleteForm(id);
  });
}

// Add function to call the delete API
async function deleteForm(id) 
{
  try 
  {
    await axios.delete(`/api/forms/${id}`);
    forms.value = forms.value.filter(form => form.id !== id);
    $q.notify({
      color: 'positive',
      position: 'top',
      message: 'Form deleted successfully.',
      icon: 'check_circle'
    });
  }
  catch (error) 
  {
    console.error(`Error deleting form ${id}:`, error);
    const errorMessage = error.response?.data?.error || 'Failed to delete form. Please try again.';
    $q.notify({
      color: 'negative',
      position: 'top',
      message: errorMessage,
      icon: 'report_problem'
    });
  }
}

// Add function to format date
function formatDate(date) 
{
  return new Date(date).toLocaleString();
}

onMounted(fetchForms);
</script>
