<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 }} Document
        </span>
      </v-row>
    </v-toolbar>
    <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="Document Attachment" />
          <InputFileV2
            v-model="document.attachment"
            :multiple="false"
            :max-length="10"
            title="Upload Files"
            accept=".pdf,.csv,.doc,.docx"
          />
        </v-col>

        <v-col cols="12" class="px-6">
          <InputLabel class="text-capitalize" title="Document Name" />
          <v-text-field
            v-model.trim="document.name"
            density="comfortable"
          ></v-text-field>
        </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"
            :disabled="disable"
          >
            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 ||
              document.attachment.length == 0 ||
              document.name == ''
            "
            @click="submit"
            :loading="disable"
          >
            Submit
          </v-btn>
        </v-col>
      </v-row>
    </v-toolbar>
  </v-card>
</template>
<script setup lang="ts">
const prop = defineProps({
  mode: {
    type: String,
    default: "add",
  },
  parentId: {
    type: String,
    default: "",
  },
  document: {
    type: Object as PropType<TDocument>,
    default: () => ({
      name: "",
      attachment: [],
      type: "",
    }),
  },
});

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

const { add, updateById } = useDocument();
const { getFileById } = useFile();

const validForm = ref(false);
const disable = ref(false);
const message = ref("");

const document = ref<Record<string, any>>({
  name: "",
  attachment: [],
  type: "",
});

const route = useRoute();
const siteId = route.params.site as string;
const orgId = route.params.org as string;
const routeParentId = computed(() =>
  typeof route.query.parentId === "string" ? route.query.parentId : ""
);
const effectiveParentId = computed(() => prop.parentId || routeParentId.value);

if (prop.mode === "edit") {
  document.value.name = prop.document.name;
  document.value.attachment = [prop.document.attachment];
  document.value.type = prop.document.type;
}

watch(
  () => document.value.attachment,
  async (newVal) => {
    if (newVal && prop.mode !== "edit") {
      const fileId = Array.isArray(newVal) ? newVal[0] : newVal;
      const fileData = await getFileById(fileId);
      if (fileData) {
        document.value.name = fileData.data.name;
      }
    }
  }
);

function deriveTypeFromFilename(name = "") {
  const n = String(name).toLowerCase();
  if (n.endsWith(".pdf")) return "pdf";
  if (n.endsWith(".csv")) return "csv";
  if (n.endsWith(".doc") || n.endsWith(".docx")) return "doc";
  return "";
}

function cancel() {
  //   createMore.value = false;
  message.value = "";
  emit("cancel");
}

async function submit() {
  disable.value = true;
  try {
    if (prop.mode === "add") {
      const fileId = Array.isArray(document.value.attachment)
        ? document.value.attachment[0]
        : document.value.attachment;

      const fileData = await getFileById(fileId);
      const fileName = fileData?.data?.name || String(fileId || "");
      const derivedType = deriveTypeFromFilename(fileName);

      if (!derivedType) {
        throw new Error("Unsupported file type. Allowed: pdf, csv, doc.");
      }

      const payload = {
        name: document.value.name,
        attachment: document.value.attachment,
        type: derivedType,
        size: fileData?.data?.size ?? fileData?.data?.file_size ?? 0,
        status: "active",
        org: orgId,
        site: siteId,
        parentId: effectiveParentId.value,
      };

      await add(payload);
    }

    if (prop.mode === "edit") {
      const fileId = Array.isArray(document.value.attachment)
        ? document.value.attachment[0]
        : document.value.attachment;

      let payload: Record<string, any> = {
        name: document.value.name,
        attachment: document.value.attachment,
      };

      if (fileId) {
        const fileData = await getFileById(fileId);
        const fileName = fileData?.data?.name || String(fileId || "");
        const derivedType = deriveTypeFromFilename(fileName);
        if (derivedType) payload.type = derivedType;
        payload.size = fileData?.data?.size ?? fileData?.data?.file_size ?? 0;
      }

      await updateById(prop.document._id ?? "", payload);
    }

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