<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 }} Block {{ (prop.mode === "edit" && building.block) ? `- ${building.block}` : "" }}
        </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-row no-gutters class="px-6 pt-4">
          <v-col cols="12" class="mt-2">
            <v-row no-gutters>
              <InputLabel class="text-capitalize font-weight-bold" title="Block Name" required />
              <v-col cols="12">
                <v-text-field v-model="building.name" density="comfortable" :rules="[requiredRule]"></v-text-field>
              </v-col>
            </v-row>
          </v-col>

          <v-col v-if="prop.mode === 'add'" cols="12">
            <v-row>
              <v-col cols="6" class="mt-2">
                <v-row no-gutters>
                  <InputLabel class="text-capitalize font-weight-bold" title="Block No." required />
                  <v-col cols="12">
                    <v-select v-model.number="building.block" :items="blocks" item-title="label" item-value="value"
                      density="comfortable" :rules="[
                        requiredRule,
                        () =>
                          (building.block && building.block > 0) ||
                          'Block is required',
                      ]" type="number">
                      <template v-slot:item="{ props: itemProps, item }">
                        <v-list-item v-bind="itemProps" :disabled="item?.raw?.disabled"></v-list-item>
                      </template>

                    </v-select>
                  </v-col>
                </v-row>
              </v-col>

              <v-col cols="6" class="mt-2">
                <v-row no-gutters>
                  <InputLabel class="text-capitalize font-weight-bold" title="No. of Levels" required />
                  <v-col cols="12">
                    <v-text-field v-model.number="buildingLevels" density="comfortable" :rules="[requiredRule]"
                      type="number" @update:model-value="setBuildingLevels()"></v-text-field>
                  </v-col>
                </v-row>
              </v-col>
            </v-row>
          </v-col>

          <!-- <v-col v-if="buildingLevels &&" cols="12">
            <v-row justify="center">
              <v-col cols="6">
                <v-btn block color="primary" variant="text" class="text-none font-weight-bold" text="Set level labels"
                  @click="show = !show"></v-btn>
              </v-col>
            </v-row>
          </v-col> -->
        </v-row>

        <v-row no-gutters v-if="building.levels.length > 0 || newLevelsArray.length > 0" class="mt-2">
          <InputLabel class="text-capitalize font-weight-bold px-6 mb-2" title="Levels" />
        </v-row>

        <v-expand-transition>
          <v-row v-if="prop.mode === 'edit'" no-gutters class="px-6">
            <template v-for="(level, levelIndex) in building.levels" :key="levelIndex">
              <v-col cols="12">
                <v-row no-gutters>
                  <v-col :cols="prop.mode === 'edit' ? 10 : 12">
                    <v-text-field v-model.trim="building.levels[levelIndex].name" density="comfortable"></v-text-field>
                  </v-col>
                  <v-col v-if="prop.mode === 'edit'" cols="2" class="d-flex align-center pb-5 justify-end">
                    <v-btn icon variant="text" color="error" :disabled="disable"
                      @click="openDeleteLevelPrompt(levelIndex)">
                      <v-icon icon="mdi-trash-can-outline"></v-icon>
                    </v-btn>
                  </v-col>
                </v-row>
              </v-col>
            </template>
          </v-row>
        </v-expand-transition>



        <v-row no-gutters class="px-6 w-100">
          <v-row no-gutters v-for="(newLevelsItem, index) in newLevelsArray" :key="index" :cols="12" class="w-100">
            <v-col :cols="prop.mode === 'edit' ? 10 : 12">
              <v-text-field v-model.trim="newLevelsArray[index]" density="comfortable"></v-text-field>
            </v-col>
            <v-col v-if="prop.mode === 'edit'" cols="2" class="d-flex align-center pb-5 justify-end">
              <v-btn icon variant="text" color="error" @click="newLevelsArray.splice(index, 1)">
                <v-icon icon="mdi-trash-can-outline"></v-icon>
              </v-btn>
            </v-col>
          </v-row>
        </v-row>

        <v-row v-if="prop.mode === 'edit'" no-gutters class="px-6 w-100">
          <v-col cols="10">
            <v-text-field v-model.trim="activeNewLevelInput" density="comfortable" class="w-100"
              placeholder="Add new level" @click="addNewLevelErrorMessage = ''"></v-text-field>
          </v-col>
          <v-col cols="2" class="d-flex align-center pb-5 justify-end">
            <v-btn icon variant="text" @click="addNewLevel()">
              <v-icon icon="mdi-plus"></v-icon>
            </v-btn>
          </v-col>
        </v-row>
        <v-row v-if="prop.mode === 'edit'" no-gutters class="px-6 mb-2">
          <span class="text-caption text-error">
            {{ addNewLevelErrorMessage }}
          </span>
        </v-row>




        <v-col cols="12" class="px-6">
          <InputLabel class="text-capitalize font-weight-bold" title="Building Floor plan" />
          <InputFileV2 v-model="building.buildingFiles" :multiple="true" accept="*" :max-length="10"
            title="Upload Files" />
        </v-col>

        <v-col cols="12" class="mt-2">
          <v-checkbox v-model="createMore" density="comfortable" hide-details>
            <template #label>
              <span class="text-subtitle-2 font-weight-bold">
                Create more
              </span>
            </template>
          </v-checkbox>
        </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"
            @click="submit" :loading="disable">
            Submit
          </v-btn>
        </v-col>
      </v-row>
    </v-toolbar>

    <ConfirmDialog v-model="confirmDeleteLevelDialog" :loading="loading.deletingLevel" width="450" persistent>
      <template #title>
        Delete Level
      </template>

      <template #description>
        Are you sure you want to delete {{ levelPendingDeleteName || "this level" }}?
      </template>

      <template #footer>
        <v-row no-gutters class="w-100">
          <v-col cols="6">
            <v-btn tile block size="48" variant="text" class="text-none" :disabled="loading.deletingLevel"
              @click="closeDeleteLevelPrompt">
              Cancel
            </v-btn>
          </v-col>

          <v-col cols="6">
            <v-btn tile block size="48" variant="flat" color="error" class="text-none" :loading="loading.deletingLevel"
              :disabled="loading.deletingLevel" @click="confirmDeleteLevel">
              Delete
            </v-btn>
          </v-col>
        </v-row>
      </template>
    </ConfirmDialog>

    <Snackbar v-model="deleteLevelToast.show" :text="deleteLevelToast.message" :color="deleteLevelToast.color" />
  </v-card>
</template>

<script setup lang="ts">
import InputLabel from './InputLabel.vue';

const prop = defineProps({
  site: {
    type: String,
    default: "",
  },
  mode: {
    type: String,
    default: "add",
  },
  building: {
    type: Object as PropType<TBuilding>,
    default: () => ({
      site: "",
      name: "",
      block: null,
      levels: [],
      buildingFiles: []
    }),
  },
  blocks: {
    type: Array as PropType<TBuilding[]>,
    default: () => [],
  },
});

const { getSiteById } = useSite();
const { getFileById } = useFile();
const { deleteById, batchUpdateLevels } = useBuildingLevel();

const site = ref<TSite | null>(null);

const { data: getSiteReq } = useLazyAsyncData(
  "get-site-by-id-" + prop.site,
  async () => getSiteById(prop.site)
);

watchEffect(() => {
  if (getSiteReq.value) {
    site.value = getSiteReq.value;
  }
});

const blocks = computed(() => {
  if (!site.value) return [];
  // return 
  // return [ { label: "1", value: 1, disabled: true }, { label: "2", value: 2 }, { label: "3", value: 3 } ];
  const array = Array.from({ length: site.value?.metadata?.block || 0 }, (_, i) => i + 1);

  const formattedArray = array.map((num) => {
    const isDisabled = prop.blocks.some((block) => block.block === num)
    return {
      label: num.toString(),
      value: num,
      disabled: isDisabled
    };
  });

  return formattedArray;
});

const emit = defineEmits(["cancel", "success", "success:create-more", "refresh"]);

const validForm = ref(false);

const buildingLevels = ref(0);
const newLevelsArray = ref<string[]>([])
const activeNewLevelInput = ref<string>("")
const addNewLevelErrorMessage = ref("");

const loading = reactive({
  deletingLevel: false,
});

const deleteLevelToast = reactive({
  show: false,
  message: "",
  color: "success" as "success" | "error",
});

const show = ref(false);
const confirmDeleteLevelDialog = ref(false);
const levelPendingDeleteIndex = ref<number | null>(null);
const levelActionLoading = ref(false);

const levelPendingDeleteName = computed(() => {
  if (levelPendingDeleteIndex.value === null) return "";
  return building.value.levels[levelPendingDeleteIndex.value]?.name ?? "";
});

function setBuildingLevels() {
  newLevelsArray.value = [];
  for (let index = 0; index < buildingLevels.value; index++) {
    newLevelsArray.value.push(`Lvl${index + 1}`);
  }
}

// function addNewLevels() {
//   const levelsToAdd = newLevelsInput.value
//     .split(/\r?\n|,/)
//     .map((item) => item.trim())
//     .filter(Boolean);

//   if (!levelsToAdd.length) return;
//   buildingLevels.value = building.value.levels.length;
//   newLevelsInput.value = "";
// }

function openDeleteLevelPrompt(levelIndex: number) {
  levelPendingDeleteIndex.value = levelIndex;
  confirmDeleteLevelDialog.value = true;
}

function closeDeleteLevelPrompt() {
  confirmDeleteLevelDialog.value = false;
  levelPendingDeleteIndex.value = null;
}

function showDeleteLevelToast(message: string, color: "success" | "error") {
  deleteLevelToast.message = message;
  deleteLevelToast.color = color;
  deleteLevelToast.show = true;
}

async function deleteLevelPlaceholder(levelName: string, levelIndex: number) {
  // Placeholder integration for future delete-level API call.
  return { success: true, levelName, levelIndex };
}



const building = ref<TBuilding>({
  site: "",
  name: "",
  block: null,
  levels: [],
  buildingFiles: []
});

const initialBuildingLevels = ref([])

// Normalize buildingFiles: extract IDs for InputFileV2, keep names in a separate map
const buildingFilesNames = ref<Record<string, string>>({});

building.value.site = prop.site;
if (prop.mode === "edit") {
  building.value = JSON.parse(JSON.stringify(prop.building));
  building.value.levels = building.value.levels.map((level: any) => ({ _id: level._id, name: level.name }));  //temporary
  buildingLevels.value = building.value.levels.length;
  initialBuildingLevels.value = JSON.parse(JSON.stringify(building.value.levels));

  const rawFiles = building.value.buildingFiles as any[];
  if (rawFiles?.length && typeof rawFiles[0] === 'object') {
    rawFiles.forEach((f: { id: string; name: string }) => {
      buildingFilesNames.value[f.id] = f.name ?? "";
    });
    building.value.buildingFiles = rawFiles.map((f: { id: string }) => f.id);
  }
}

watch(
  () => building.value.buildingFiles as string[],
  async (ids) => {
    for (const id of ids) {
      if (!buildingFilesNames.value[id]) {
        try {
          const meta = await getFileById(id) as any;
          buildingFilesNames.value[id] = meta?.data?.name ?? meta?.name ?? "";
        } catch {
          buildingFilesNames.value[id] = "";
        }
      }
    }
  },
  { deep: true }
);

const createMore = ref(false);
const disable = ref(false);

const { requiredRule } = useUtils();

const message = ref("");

const { createBuilding, updateById } = useBuilding();

async function submit() {
  disable.value = true;

  try {
    if (prop.mode === "add") {
      const buildingPayload = { ...building.value };

      let payload: TBuildingPayload = {
        site: buildingPayload.site,
        name: buildingPayload.name,
        block: buildingPayload.block,
        levels: [...newLevelsArray.value],
        buildingFiles: (building.value.buildingFiles as string[] || []).map((id) => ({ id, name: buildingFilesNames.value[id] ?? "" }))
      };

      await createBuilding(payload);
    }

    if (prop.mode === "edit") {

      console.log('Updating building with levels:', building.value.levels);

      if (JSON.stringify(initialBuildingLevels.value) !== JSON.stringify(building.value.levels)) {
        await batchUpdateLevels(building.value.levels as { _id: string; name: string }[]);
      }

      const newLevels = [...newLevelsArray.value, ...(activeNewLevelInput.value.trim() ? [activeNewLevelInput.value.trim()] : [])];

      await updateById(building.value._id ?? "", {
        name: building.value.name,
        block: building.value.block,
        // levels: building.value.levels,
        buildingFiles: (building.value.buildingFiles as string[] || []).map((id) => ({ id, name: buildingFilesNames.value[id] ?? "" })),
        ...(newLevels.length > 0 ? { levels: newLevels } : {})
      });
    }

    if (createMore.value) {
      building.value.levels = [];
      building.value.name = "";
      building.value.block = null;

      message.value = "";
      emit("success:create-more");
      return;
    }

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


const addNewLevel = () => {
  if (!activeNewLevelInput.value.trim()) {
    addNewLevelErrorMessage.value = "Please fill in the current new level before adding another.";
    return;
  }
  newLevelsArray.value.push(activeNewLevelInput.value);
  activeNewLevelInput.value = "";
}

const confirmDeleteLevel = async () => {
  const levelIndex = levelPendingDeleteIndex.value;
  if (levelIndex === null) {
    console.error("No level selected for deletion.");
    showDeleteLevelToast("No level selected for deletion.", "error");
    return;
  }
  const levelId = building.value.levels[levelIndex]._id;
  if (!levelId) {
    console.error("Level ID is missing. Cannot delete level.");
    showDeleteLevelToast("Level ID is missing. Cannot delete level.", "error");
    return;
  }

  try {
    loading.deletingLevel = true;
    await deleteById(levelId);
    const index = building.value.levels.findIndex(level => level._id === levelId);
    closeDeleteLevelPrompt();
    if (index !== -1) {
      building.value.levels.splice(index, 1);
      buildingLevels.value = building.value.levels.length;
    }
    emit('refresh')
    showDeleteLevelToast("Level deleted successfully.", "success");
  } catch (error: any) {
    console.error("Failed to delete level:", error);
    const errorMessage = error.response?._data?.message || "Failed to delete level";
    showDeleteLevelToast(errorMessage, "error");
  } finally {
    loading.deletingLevel = false;
  }


}

watch(buildingLevels, (newVal) => {
  setTimeout(() => {
    show.value = newVal > 0 && !!newVal;
  }, 500);
});

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