<template>
  <v-row no-gutters>
    <v-col cols="12" class="mb-2">
      <v-row no-gutters>
        <v-btn
          class="text-none"
          rounded="pill"
          variant="tonal"
          size="large"
          @click="setOnlineForm()"
          v-if="canCreate && canCreateOnlineFormConfiguration"
        >
          Add Online Form
        </v-btn>
      </v-row>
    </v-col>
    <v-col cols="12">
      <v-card
        width="100%"
        variant="outlined"
        border="thin"
        rounded="lg"
        :loading="loading"
      >
        <v-toolbar density="compact" color="grey-lighten-4">
          <template #prepend>
            <v-btn
              fab
              icon
              density="comfortable"
              @click="getOnlineFormConfigurations"
            >
              <v-icon>mdi-refresh</v-icon>
            </v-btn>
            <v-text-field
              v-model="search"
              density="compact"
              variant="outlined"
              placeholder="Search..."
              prepend-inner-icon="mdi-magnify"
              clearable
              hide-details
              style="width: 220px; margin-left: 12px;"
            />
          </template>

          <template #append>
            <v-row no-gutters justify="end" align="center">
              <span class="mr-2 text-caption text-fontgray">
                {{ pageRange }}
              </span>
              <local-pagination
                v-model="page"
                :length="pages"
                @update:value="getOnlineFormConfigurations"
              />
            </v-row>
          </template>
        </v-toolbar>
        <v-data-table
          :headers="headers"
          :items="items"
          item-value="_id"
          items-per-page="10"
          fixed-header
          hide-default-footer
          @click:row="tableRowClickHandler"
          style="max-height: calc(100vh - (200px))"
        >
          <template v-slot:item.createdAt="{ item }">
            {{ formatDateDDMMYYYYLocal(item.createdAt) }}
          </template>
          <template v-slot:item.status="{ item }">
            {{ item.status ? item.status.charAt(0).toUpperCase() + item.status.slice(1) : "N/A" }}
          </template></v-data-table
        >
      </v-card></v-col
    >

    <!-- Create Dialog -->
    <v-dialog v-model="createDialog" width="450" persistent>
      <OnlineFormConfigurationForm
        mode="add"
        @cancel="createDialog = false"
        @success="successCreate()"
      />
    </v-dialog>

    <!-- Edit Dialog -->
    <v-dialog v-model="editDialog" width="450" persistent>
      <OnlineFormConfigurationForm
        mode="edit"
        @cancel="editDialog = false"
        @success="successUpdate()"
        :online-form="selectedOnlineForm"
      />
    </v-dialog>

    <!-- Preview Dialog -->
    <v-dialog v-model="previewDialog" width="450" persistent>
      <v-card width="100%">
        <v-card-text style="max-height: 100vh; overflow-y: auto" class="pb-0">
          <v-row no-gutters class="mb-4">
            <v-col cols="12">
              <strong>Name:</strong> {{ selectedOnlineForm?.formType ?? "N/A" }}
            </v-col>
            <v-col v-if="selectedOnlineForm?.attachment" cols="12">
              <strong>Document: </strong>
              <NuxtLink
                :to="getFileUrl(selectedOnlineForm.attachment)"
                external
                target="_blank"
              >
                View Document
              </NuxtLink>
            </v-col>
            <v-col cols="12">
              <strong>Status:</strong> {{ selectedOnlineForm?.status ? selectedOnlineForm.status.charAt(0).toUpperCase() + selectedOnlineForm.status.slice(1) : "N/A" }}
            </v-col>
            <v-col cols="12">
              <strong>Inputs:</strong>
              <div
                v-if="selectedOnlineForm?.inputs?.length"
                class="d-flex flex-wrap gap-2 mt-1"
              >
                <v-chip
                  v-for="(input, index) in selectedOnlineForm.inputs"
                  :key="index"
                  color="primary"
                  variant="elevated"
                  size="small"
                  class="me-1 mb-2"
                >
                  {{ input.label }}
                </v-chip>
              </div>
            </v-col>
          </v-row>
        </v-card-text>
        <v-toolbar class="pa-0" density="compact">
          <v-row no-gutters>
            <v-col cols="6" class="pa-0">
              <v-btn
                block
                variant="text"
                class="text-none"
                size="large"
                @click="previewDialog = false"
                height="48"
              >
                Close
              </v-btn>
            </v-col>
            <v-col cols="6" class="pa-0" v-if="canUpdate">
              <v-menu>
                <template #activator="{ props }">
                  <v-btn
                    block
                    variant="flat"
                    color="black"
                    class="text-none"
                    height="48"
                    v-bind="props"
                    tile
                    :disabled="
                      !canUpdateOnlineFormConfiguration &&
                      !canDeleteOnlineFormConfiguration
                    "
                  >
                    More actions
                  </v-btn>
                </template>
                <v-list class="pa-0">
                  <v-list-item @click="previewDialog = false; formRenderPreviewDialog = true">
                    <v-list-item-title class="text-subtitle-2">
                      Preview
                    </v-list-item-title>
                  </v-list-item>

                  <v-list-item
                    v-if="canUpdateOnlineFormConfiguration"
                    @click="openEditDialog()"
                  >
                    <v-list-item-title class="text-subtitle-2">
                      Edit
                    </v-list-item-title>
                  </v-list-item>

                  <v-list-item
                    v-if="canDeleteOnlineFormConfiguration"
                    class="text-red"
                    @click="openDeleteDialog()"
                  >
                    <v-list-item-title class="text-subtitle-2">
                      Delete
                    </v-list-item-title>
                  </v-list-item>
                </v-list>
              </v-menu>
            </v-col>
          </v-row>
        </v-toolbar>
      </v-card>
    </v-dialog>

    <!-- Form Render Preview Dialog -->
    <OnlineFormRenderPreview
      v-model="formRenderPreviewDialog"
      :form="selectedOnlineForm"
    />

    <!-- Delete Dialog -->
    <v-dialog
      v-model="confirmDialog"
      :loading="deleteLoading"
      width="450"
      persistent
    >
      <v-card width="100%">
        <v-toolbar density="compact" class="pl-4">
          <span class="font-weight-medium text-h5">Delete Online Form</span>
        </v-toolbar>
        <v-card-text>
          <p class="text-subtitle-2 text-center">
            Are you sure you want to delete this online form? This action cannot
            be undone.
          </p>

          <v-row v-if="message" no-gutters justify="center" class="mt-4">
            <span class="text-caption text-error text-center">
              {{ message }}
            </span>
          </v-row>
        </v-card-text>
        <v-toolbar density="compact">
          <v-row no-gutters>
            <v-col cols="6">
              <v-btn
                tile
                block
                size="48"
                variant="text"
                class="text-none"
                @click="confirmDialog = false"
                :disabled="deleteLoading"
              >
                Close
              </v-btn>
            </v-col>
            <v-col cols="6">
              <v-btn
                tile
                block
                size="48"
                color="black"
                variant="flat"
                class="text-none"
                :loading="deleteLoading"
                :disabled="deleteLoading"
                @click="handleDeleteOnlineFormConfiguration()"
              >
                Delete Online Form
              </v-btn>
            </v-col>
          </v-row>
        </v-toolbar>
      </v-card>
    </v-dialog>

    <Snackbar v-model="messageSnackbar" :text="message" :color="messageColor" />
  </v-row>
</template>
<script setup lang="ts">
import OnlineFormConfigurationForm from "./OnlineFormConfigurationForm.vue";
import OnlineFormRenderPreview from "./OnlineFormRenderPreview.vue";
import useFile from "../composables/useFile";
import useOnlineFormConfiguration from "../composables/useOnlineFormConfiguration";

definePageMeta({
  middleware: ["01-auth", "02-org"],
  memberOnly: true,
});
const props = defineProps({
  headers: {
    type: Array as PropType<Array<Record<string, any>>>,
    default: () => [
      {
        title: "Name",
        value: "formType",
      },
      { title: "Date Created", value: "createdAt" },
      { title: "Status", value: "status" },
    ],
  },
  canCreate: {
    type: Boolean,
    default: true,
  },
  canUpdate: {
    type: Boolean,
    default: true,
  },
  canDelete: {
    type: Boolean,
    default: true,
  },
  canCreateOnlineFormConfiguration: {
    type: Boolean,
    default: true,
  },
  canUpdateOnlineFormConfiguration: {
    type: Boolean,
    default: true,
  },
  canDeleteOnlineFormConfiguration: {
    type: Boolean,
    default: true,
  },
});

const { getAll: _getAll, deleteById: _deleteById } = useOnlineFormConfiguration();
const { getFileUrl } = useFile();

const page = ref(1);
const pages = ref(0);
const pageRange = ref("-- - -- of --");
const search = ref("");

const message = ref("");
const messageSnackbar = ref(false);
const messageColor = ref("");

const route = useRoute();
const siteId = route.params.site as string;
const orgId = route.params.org as string;

const items = ref<Array<Record<string, any>>>([]);

const { formatDateDDMMYYYYLocal } = useUtils();

const {
  data: getOnlineFormConfigurationReq,
  refresh: getOnlineFormConfigurations,
  status: getAllReqStatus,
} = useLazyAsyncData("get-all-online-form-configuration", () =>
  _getAll({
    page: page.value,
    search: search.value,
    status: "active",
    org: orgId,
    site: siteId,
  })
);

const loading = computed(() => getAllReqStatus.value === "pending");

let searchDebounce: ReturnType<typeof setTimeout> | null = null;
watch(search, () => {
  if (searchDebounce) clearTimeout(searchDebounce);
  searchDebounce = setTimeout(() => {
    page.value = 1;
    getOnlineFormConfigurations();
  }, 400);
});

watchEffect(() => {
  if (getOnlineFormConfigurationReq.value) {
    items.value = getOnlineFormConfigurationReq.value.items;
    pages.value = getOnlineFormConfigurationReq.value.pages;
    pageRange.value = getOnlineFormConfigurationReq.value.pageRange;
  }
});

const createDialog = ref(false);
const editDialog = ref(false);
const previewDialog = ref(false);
const formRenderPreviewDialog = ref(false);
const selectedOnlineForm = ref<TOnlineForm>({
  _id: "",
  name: "",
  createdAt: "",
  status: "",
  attachment: "",
  inputs: [
    {
      label: "",
      dataType: "",
      required: false,
      multiple: false,
    },
  ],
});
const deleteLoading = ref(false);
const confirmDialog = ref(false);
const selectedOnlineFormId = ref<string | null>(null);

function parseFieldsToInputs(fields: Record<string, string>): any[] {
  return Object.keys(fields)
    .filter((key) => key !== "attachment")
    .sort((a, b) => Number(a) - Number(b))
    .map((key) => {
      try { return JSON.parse(fields[key]); } catch { return fields[key]; }
    });
}

function tableRowClickHandler(_: any, data: any) {
  const item = data.item;
  selectedOnlineForm.value = {
    ...item,
    inputs: parseFieldsToInputs(item.fields ?? {}),
    attachment: item.fields?.["attachment"] ?? "",
  } as TOnlineForm;
  previewDialog.value = true;
}

function setOnlineForm({
  mode = "create",
  dialog = true,
  data = {} as any,
} = {}) {
  if (mode === "create") {
    createDialog.value = dialog;
  } else if (mode === "edit") {
    editDialog.value = dialog;
    selectedOnlineForm.value = data;
  } else if (mode === "preview") {
    previewDialog.value = dialog;
    selectedOnlineForm.value = data;
  }
}

function openDeleteDialog() {
  confirmDialog.value = true;
  message.value = "";
}

function openEditDialog() {
  editDialog.value = true;
}

function successCreate() {
  createDialog.value = false;
  getOnlineFormConfigurations();
  showMessage("Online form configuration created successfully!", "success");
}

function showMessage(msg: string, color: string) {
  message.value = msg;
  messageColor.value = color;
  messageSnackbar.value = true;
}

async function handleDeleteOnlineFormConfiguration() {
  deleteLoading.value = true;
  try {
    await _deleteById(selectedOnlineForm.value._id ?? "");
    await getOnlineFormConfigurations();
    selectedOnlineFormId.value = null;
    confirmDialog.value = false;
    previewDialog.value = false;
    showMessage("Online form configuration deleted successfully!", "success");
  } catch (error: any) {
    showMessage(
      error?.response?._data?.message || "Failed to delete online form configuration",
      "error"
    );
  } finally {
    deleteLoading.value = false;
  }
}

function successUpdate() {
  editDialog.value = false;
  previewDialog.value = false;
  getOnlineFormConfigurations();
  showMessage("Online form configuration updated successfully!", "success");
}
</script>
