<template>
  <v-card width="100%">
    <v-toolbar>
      <v-row no-gutters class="fill-height px-6" align="center">
        <span class="font-weight-bold text-h5 text-capitalize">
          {{ prop.mode }} Online Form
        </span>
      </v-row>
    </v-toolbar>
    <v-col v-if="prop.mode !== 'edit'" cols="12" class="px-6 pt-4 pb-0">
      <InputLabel title="Form Template" />
      <v-list
        density="compact"
        lines="one"
        max-height="160"
        style="overflow-y: auto; border: 1px solid rgba(0,0,0,0.18); border-radius: 4px;"
        class="pa-0"
      >
        <v-list-item
          v-if="availableTemplateNames.length === 0"
          disabled
          title="All templates have already been created"
          class="text-caption text-medium-emphasis"
        />
        <v-list-item
          v-for="name in availableTemplateNames"
          :key="name"
          :title="name"
          :active="selectedTemplate === name"
          active-color="primary"
          class="text-caption"
          @click="selectedTemplate = name; applyTemplate(name)"
        />
      </v-list>
    </v-col>
    <v-divider v-if="prop.mode !== 'edit'" class="mt-3" />

    <v-card-text style="max-height: 100vh; overflow-y: auto" class="pa-0">
      <v-form v-model="validForm" :disabled="disable">
        <v-col cols="12" class="px-6">
          <InputLabel class="text-capitalize" title="Attachment (Optional)" />

          <div v-if="onlineForm.attachment" class="d-flex align-center" style="gap:8px">
            <v-card
              variant="outlined"
              border="thin"
              class="px-3 flex-grow-1 text-caption"
              height="40"
              :href="getFileUrl(onlineForm.attachment)"
              target="_blank"
            >
              <v-row no-gutters class="fill-height" align="center" style="gap:6px">
                <v-icon size="15">mdi-file-document-outline</v-icon>
                {{ attachmentFileName || 'View attachment' }}
                <v-icon size="13" class="ml-auto">mdi-open-in-new</v-icon>
              </v-row>
            </v-card>
            <v-btn icon variant="text" size="small" density="comfortable" :disabled="disable" @click="clearAttachment">
              <v-icon size="17">mdi-close</v-icon>
            </v-btn>
          </div>

          <div
            v-else
            class="upload-drop-zone"
            :class="{ 'drag-over': isDragOver, 'is-uploading': isUploading }"
            @dragover.prevent="isDragOver = true"
            @dragleave.prevent="isDragOver = false"
            @drop.prevent="handleDrop"
            @click="fileInputRef?.click()"
          >
            <v-progress-circular v-if="isUploading" indeterminate size="24" width="2" color="primary" class="mb-1" />
            <v-icon v-else size="26" :color="isDragOver ? 'primary' : undefined" class="mb-1 text-medium-emphasis">
              mdi-cloud-upload-outline
            </v-icon>
            <span class="text-caption text-medium-emphasis">
              {{ isUploading ? 'Uploading…' : 'Drop file here or click to browse' }}
            </span>
            <input
              ref="fileInputRef"
              type="file"
              accept=".pdf,application/pdf,image/*"
              style="display:none"
              @change="handleFileInputChange"
            />
          </div>

          <span v-if="attachmentError" class="text-caption text-error d-block mt-1">{{ attachmentError }}</span>
        </v-col>

        <v-col cols="12" class="px-6">
          <InputLabel class="text-capitalize" title="Name" />
          <v-text-field
            v-model.trim="onlineForm.formType"
            density="comfortable"
          ></v-text-field>
        </v-col>

        <template v-for="(inputLabel, inputLabelIndex) in onlineForm.inputs">
          <v-row class="px-6 mb-0" align="center" no-gutters>
            <v-col>
              <span class="text-caption font-weight-medium text-medium-emphasis">
                Field {{ inputLabelIndex + 1 }}
              </span>
            </v-col>
            <v-col cols="auto">
              <v-btn
                icon
                size="small"
                variant="text"
                color="error"
                :disabled="onlineForm.inputs.length === 1"
                @click="onlineForm.inputs.splice(inputLabelIndex, 1)"
              >
                <v-icon size="18">mdi-delete-outline</v-icon>
              </v-btn>
            </v-col>
          </v-row>
          <v-row class="px-6">
            <v-col cols="6">
              <InputLabel title="Label" />
              <v-text-field
                v-model.trim="inputLabel.label"
                density="comfortable"
              />
            </v-col>
            <v-col cols="6">
              <InputLabel title="Data Type" />
              <v-select v-model="inputLabel.dataType" :items="dataTypes" />
            </v-col>
            <v-col v-if="inputLabel.dataType === 'Select'" cols="12">
              <InputLabel title="Options" />
              <v-combobox
                v-model="inputLabel.options"
                chips
                closable-chips
                multiple
                density="comfortable"
                variant="outlined"
                placeholder="Type an option and press Enter"
                hint="Press Enter after each option to add it"
                persistent-hint
              />
            </v-col>
            <v-col cols="6">
              <InputLabel title="Required" />
              <v-checkbox v-model="inputLabel.required" />
            </v-col>
            <v-col cols="6">
              <InputLabel title="Multiple" />
              <v-checkbox v-model="inputLabel.multiple" />
            </v-col>
          </v-row>
          <v-divider class="my-3" />
        </template>

        <v-col cols="12" class="px-6 pb-4">
          <v-btn
            block
            variant="outlined"
            color="primary"
            class="text-none"
            prepend-icon="mdi-plus"
            @click="addNewInput"
          >
            Add Field
          </v-btn>
        </v-col>

        <v-col cols="12">
          <v-row no-gutters>
            <v-col cols="12" class="text-center">
              <span
                class="text-none text-subtitle-2 font-weight-medium text-error"
              >
                {{ message }}
              </span>
            </v-col>
          </v-row>
        </v-col>
      </v-form>
    </v-card-text>
    <v-toolbar density="compact">
      <v-row no-gutters>
        <v-col cols="6">
          <v-btn
            tile
            block
            variant="text"
            class="text-none"
            size="48"
            @click="cancel"
          >
            Cancel
          </v-btn>
        </v-col>
        <v-col cols="6">
          <v-btn
            tile
            block
            variant="flat"
            color="black"
            class="text-none"
            size="48"
            :disabled="!validForm || disable || onlineForm.formType == ''"
            @click="submit"
            :loading="disable"
          >
            {{ prop.mode === "edit" ? "Update" : "Submit" }}
          </v-btn>
        </v-col>
      </v-row>
    </v-toolbar>
  </v-card>
</template>
<script setup lang="ts">
import useFile from "../composables/useFile";
import useOnlineFormConfiguration from "../composables/useOnlineFormConfiguration";
import useOnlineFormTemplates from "../composables/useOnlineFormTemplates";

const prop = defineProps({
  mode: {
    type: String,
    default: "add",
  },
  onlineForm: {
    type: Object as PropType<TOnlineForm>,
    default: () => ({
      name: "",
      attachment: "",
      inputs: [
        {
          label: "",
          dataType: "",
          required: true,
          multiple: false,
        },
      ],
      status: "active",
    }),
  },
});

const emit = defineEmits(["cancel", "success"]);

const validForm = ref(false);
const disable = ref(false);
const message = ref("");
const selectedTemplate = ref<string | null>(null);

const { formTemplates, templateNames } = useOnlineFormTemplates();

function applyTemplate(name: string | null) {
  if (!name) return;
  const template = formTemplates[name];
  if (!template) return;
  onlineForm.value.formType = name;
  onlineForm.value.inputs = template.map((f) => ({ ...f }));
}

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

const { addFile, getFileUrl } = useFile();
const { create: _add, updateById: _update, getAll: _getAll } = useOnlineFormConfiguration();

const { data: existingFormsData } = useLazyAsyncData(
  `online-form-configurations-filter-${siteId}-${Date.now()}`,
  () => _getAll({ site: siteId, org: orgId, status: "active", limit: 100 })
);

const availableTemplateNames = computed(() => {
  const existing = new Set(existingFormsData.value?.items?.map((f: any) => f.formType) ?? []);
  return templateNames.filter((name) => !existing.has(name));
});

const isDragOver = ref(false);
const isUploading = ref(false);
const attachmentError = ref("");
const attachmentFileName = ref("");
const fileInputRef = ref<HTMLInputElement | null>(null);

const onlineForm = ref<Record<string, any>>({
  formType: "",
  attachment: "",
  inputs: [
    {
      label: "Name",
      dataType: "Text Input",
      required: true,
      multiple: false,
    },
  ],
  status: "active",
});

const dataTypes = ref([
  "Text Input",
  "Text Area",
  "Date Input",
  "Select",
  "Checkbox",
]);

if (prop.mode === "edit") {
  onlineForm.value.attachment = prop.onlineForm.attachment;
  onlineForm.value.formType = prop.onlineForm.formType;
  onlineForm.value.inputs = prop.onlineForm.inputs;
}

function handleDrop(e: DragEvent) {
  isDragOver.value = false;
  const file = e.dataTransfer?.files[0];
  if (file) uploadAttachment(file);
}

function handleFileInputChange(e: Event) {
  const file = (e.target as HTMLInputElement).files?.[0];
  if (file) uploadAttachment(file);
}

async function uploadAttachment(file: File) {
  isUploading.value = true;
  attachmentError.value = "";
  try {
    const res = await addFile(file);
    onlineForm.value.attachment = res.id;
    attachmentFileName.value = file.name;
  } catch (e: any) {
    attachmentError.value = e?.message || "Upload failed. Please try again.";
  } finally {
    isUploading.value = false;
  }
}

function clearAttachment() {
  onlineForm.value.attachment = "";
  attachmentFileName.value = "";
  attachmentError.value = "";
  if (fileInputRef.value) fileInputRef.value.value = "";
}

function cancel() {
  emit("cancel");
}

function addNewInput() {
  onlineForm.value.inputs.push({
    label: "",
    dataType: "",
    required: true,
    multiple: false,
    options: [],
  });
}

async function submit() {
  // console.log("submit", onlineForm.value);
  disable.value = true;
  try {
    if (prop.mode === "add") {
      const fields: Record<string, string> = Object.fromEntries(
        onlineForm.value.inputs.map((input: any, i: number) => [String(i), JSON.stringify(input)])
      );
      if (onlineForm.value.attachment) fields["attachment"] = onlineForm.value.attachment;

      await _add({
        formType: onlineForm.value.formType,
        fields,
        status: "active",
        org: orgId,
        site: siteId,
      });
    }

    if (prop.mode === "edit") {
      const fields: Record<string, string> = Object.fromEntries(
        onlineForm.value.inputs.map((input: any, i: number) => [String(i), JSON.stringify(input)])
      );
      if (onlineForm.value.attachment) fields["attachment"] = onlineForm.value.attachment;

      await _update(prop.onlineForm._id ?? "", {
        _id: prop.onlineForm._id ?? "",
        formType: onlineForm.value.formType,
        fields,
        status: onlineForm.value.status || "active",
      });
    }

    emit("success");
  } catch (error: any) {
    message.value =
      error.response?._data?.message || "Failed to create document";
  } finally {
    disable.value = false;
  }
}
</script>

<style scoped>
.upload-drop-zone {
  border: 2px dashed rgba(0, 0, 0, 0.2);
  border-radius: 8px;
  padding: 18px 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  min-height: 80px;
  transition: border-color 0.2s, background-color 0.2s;
  user-select: none;
}
.upload-drop-zone:hover,
.upload-drop-zone.drag-over {
  border-color: rgb(var(--v-theme-primary));
  background-color: rgba(var(--v-theme-primary), 0.04);
}
.upload-drop-zone.is-uploading {
  pointer-events: none;
  opacity: 0.65;
}
</style>
