<template>
  <v-card width="100%" :loading="getUnitPeoplePending || loading.ownerProcessing" :disabled="loading.ownerProcessing">
    <v-toolbar>
      <v-row no-gutters class="fill-height px-6" align="center">
        <span class="font-weight-bold text-h5"> Unit Info ( {{ buildingUnit.name }} ) </span>
      </v-row>
    </v-toolbar>
    <v-toolbar density="compact">
      <v-tabs v-model="tab" class="mt-0" active-class="bg-success">
        <v-tab value="general">General</v-tab>
        <v-tab value="residents">Residents/Tenants</v-tab>
        <v-tab value="vehicles">Vehicles</v-tab>
        <v-tab value="others">Others</v-tab>
      </v-tabs>
    </v-toolbar>
    <v-card-text style="max-height: 100vh; min-height: 60svh; overflow-y: auto">
      <template v-if="tab === 'general'">
        <v-form v-model="validForm" :disabled="disable">
          <v-row>
            <v-col cols="12" md="6" lg="4" class="mt-2">
              <v-row no-gutters>
                <InputLabel class="text-capitalize font-weight-bold" title="Unit Name" />
                <v-col cols="12">
                  <v-text-field v-model="buildingUnit.name" density="comfortable"
                    :rules="[requiredRule]"></v-text-field>
                </v-col>
              </v-row>
            </v-col>

            <v-col cols="12" md="6" lg="4" class="mt-2">
              <v-row no-gutters>
                <InputLabel class="text-capitalize font-weight-bold" title="Level"/>
                <v-col cols="12">
                  <!-- <v-select v-model="buildingUnit.level" :items="buildingLevels" readonly item-title="name" class="no-pointer" item-value="_id" density="comfortable"
                    :rules="[requiredRule]"></v-select> -->
                    <v-text-field :model-value="buildingUnit.level.name" density="comfortable" readonly class="no-pointer" />
                </v-col>
              </v-row>
            </v-col>

            <v-col cols="12" md="6" lg="4">
              <v-row>
                <v-col cols="12" class="mt-2">
                  <v-row no-gutters>
                    <InputLabel class="text-capitalize font-weight-bold" title="Block Name" />
                    <v-col cols="12">
                      <v-text-field :model-value="buildingUnit.buildingName"
                        density="comfortable" readonly class="no-pointer"></v-text-field>
                    </v-col>
                  </v-row>
                </v-col>
              </v-row>
            </v-col>
          </v-row>

          <v-divider class="mb-10" />
          <v-row>
            <v-col cols="12" md="6" class="mt-2">
              <v-row no-gutters>
                <InputLabel class="text-capitalize font-weight-bold" title="Billing Address Line 1" />
                <v-col cols="12">
                  <v-text-field :model-value="buildingUnit?.site?.address?.line1" density="compact" readonly
                    class="no-pointer"></v-text-field>
                </v-col>
              </v-row>
            </v-col>
            <v-col cols="12" md="6" class="mt-2">
              <v-row no-gutters>
                <InputLabel class="text-capitalize font-weight-bold" title="Billing Address Line 2" />
                <v-col cols="12">
                  <v-text-field :model-value="buildingUnit?.site?.address?.line2" density="compact" readonly
                    class="no-pointer"></v-text-field>
                </v-col>
              </v-row>
            </v-col>
            <v-col cols="12" md="4" lg="4" class="mt-2">
              <v-row no-gutters>
                <InputLabel class="text-capitalize font-weight-bold" title="City" />
                <v-col cols="12">
                  <v-text-field :model-value="buildingUnit?.site?.address?.city" density="compact" readonly
                    class="no-pointer"></v-text-field>
                </v-col>
              </v-row>
            </v-col>
            <v-col cols="12" md="4" lg="4" class="mt-2">
              <v-row no-gutters>
                <InputLabel class="text-capitalize font-weight-bold" title="State" />
                <v-col cols="12">
                  <v-text-field :model-value="buildingUnit?.site?.address?.state" density="compact" readonly
                    class="no-pointer"></v-text-field>
                </v-col>
              </v-row>
            </v-col>
            <v-col cols="12" md="4" lg="4" class="mt-2">
              <v-row no-gutters>
                <InputLabel class="text-capitalize font-weight-bold" title="Country" />
                <v-col cols="12">
                  <v-text-field :model-value="buildingUnit?.site?.address?.country" density="compact" readonly
                    class="no-pointer"></v-text-field>
                </v-col>
              </v-row>
            </v-col>
            <v-col cols="12" md="4" lg="4" class="mt-2">
              <v-row no-gutters>
                <InputLabel class="text-capitalize font-weight-bold" title="Postal Code" />
                <v-col cols="12">
                  <v-text-field :model-value="buildingUnit?.site?.address?.postalCode" density="compact" readonly
                    class="no-pointer"></v-text-field>
                </v-col>
              </v-row>
            </v-col>
          </v-row>
        </v-form>
      </template>

      <template v-else-if="tab === 'residents'">
        <v-card width="100%">
          <v-expansion-panels v-model="panels" variant="accordion">

            <!-- Residents -->
            <v-expansion-panel value="residents">
              <v-expansion-panel-title class="bg-primary">
                Residents ({{ unitResidentsArray.length }})
              </v-expansion-panel-title>

              <v-expansion-panel-text>
                <template v-if="unitResidentsArray.length" v-for="resident, residentIndex in unitResidentsArray"
                  :key="residentIndex">
                  <UnitPersonCard :person="resident" :readOnly="true" show-owner-option
                    @update:owner="handleUpdateOwner" :loading-owner-processing="loading.ownerProcessing" />
                  <v-divider v-if="(residentIndex + 1) !== unitResidentsArray.length" thickness="2" color="primary"
                    class="my-4" />
                </template>
                <p v-else class="font-weight-semibold  text-caption ml-2 mt-5">
                  **No residents to display**
                </p>
              </v-expansion-panel-text>
            </v-expansion-panel>

            <!-- Tenants -->
            <v-expansion-panel value="tenants">
              <v-expansion-panel-title class="bg-primary">
                Tenants ({{ unitTenantsArray.length }})
              </v-expansion-panel-title>

              <v-expansion-panel-text>
                <template v-if="unitTenantsArray.length" v-for="(tenant, tenantIndex) in unitTenantsArray"
                  :key="tenant._id || tenantIndex">
                  <UnitPersonCard :person="tenant" :readOnly="true" />
                  <v-divider v-if="(tenantIndex + 1) !== unitTenantsArray.length" thickness="2" color="primary"
                    class="my-4" />
                </template>
                <p v-else class=" font-weight-semibold text-caption ml-2 mt-5">
                  **No tenants to display**
                </p>
              </v-expansion-panel-text>
            </v-expansion-panel>
          </v-expansion-panels>
        </v-card>
      </template>
      <template v-else-if="tab === 'vehicles'">
        <TableMain :headers="vehicleHeaders" :show-header="true" :page="vehiclePage" :pages="vehicleTotalPages"
        :pageRange="vehiclePageRange"  :items="unitVehicleItems"  @refresh="getUnitVehiclesRefresh"  @update:page="handleUpdateVehiclePage">

          <template #item.status="{value}">
            <v-chip :color="formatVehicleStatus(value).color" class="ma-0" small>
              {{ formatVehicleStatus(value).label }}
            </v-chip>
          </template>
        </TableMain>
      </template>

      <template v-else-if="tab === 'others'">
        <v-row>
          <!-- <v-col cols="12" md="6" class="mt-2">
            <v-row no-gutters>
              <InputLabel class="text-capitalize font-weight-bold" title="Owner" />
              <v-col cols="12">
                <v-autocomplete v-model="buildingUnit.ownerName" v-model:search="ownerNameInput" :items="peopleItems"
                  item-title="name" return-object density="comfortable">
                </v-autocomplete>
              </v-col>
            </v-row>
          </v-col> -->

          <v-col cols="12">
            <v-row>
              <v-col cols="12" md="6" class="mt-2">
                <v-row no-gutters>
                  <InputLabel class="text-capitalize" title="Company Name" required />
                  <v-col cols="12">
                    <v-text-field v-model="buildingUnit.companyName" density="comfortable"
                      :rules="[requiredRule]"></v-text-field>
                  </v-col>
                </v-row>
              </v-col>

              <v-col cols="12" md="6" class="mt-2">
                <v-row no-gutters>
                  <InputLabel class="text-capitalize" title="Company Registration Number" />
                  <v-col cols="12">
                    <v-text-field v-model="buildingUnit.companyRegistrationNumber" density="comfortable"></v-text-field>
                  </v-col>
                </v-row>
              </v-col>
            </v-row>
          </v-col>

          <v-col cols="12">
            <v-row>
              <v-col cols="12" md="6" class="mt-2">
                <v-row no-gutters>
                  <InputLabel class="text-capitalize" title="Lease Start" required />
                  <v-col cols="12">
                    <InputDateTimePicker ref="startDateRef" v-model="buildingUnit.leaseStart" :rules="[requiredRule]" />
                  </v-col>
                </v-row>
              </v-col>

              <v-col cols="12" md="6" class="mt-2">
                <v-row no-gutters>
                  <InputLabel class="text-capitalize" title="Lease End" required />
                  <v-col cols="12">
                    <InputDateTimePicker ref="endDateRef" v-model="buildingUnit.leaseEnd" :rules="[requiredRule]" />
                  </v-col>
                </v-row>
              </v-col>

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

          <v-col cols="12" class="mt-2">
            <InputLabel class="text-capitalize d-block mb-1" title="Unit Documents" />
            <InputFileV2
              v-model="buildingUnit.buildingUnitFiles"
              :multiple="true"
              accept="*/*"
              title="Upload documents"
              :height="104"
            />
          </v-col>
        </v-row>
      </template>
    </v-card-text>

    <v-col cols="12" class="my-2">
      <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-toolbar class="pa-0" density="compact">
      <v-row no-gutters>
        <v-col :cols="canUpdateUnit || canDeleteUnit ? 6 : 12" class="pa-0">
          <v-btn block variant="text" class="text-none" size="large" @click="emit('cancel')" height="48">
            Close
          </v-btn>
        </v-col>

        <v-col v-if="canUpdateUnit || canDeleteUnit" cols="6" class="pa-0">
          <v-menu>
            <template #activator="{ props }">
              <v-btn block variant="flat" color="black" class="text-none" height="48" v-bind="props" tile
                :disabled="!canUpdateUnit && !canDeleteUnit">
                More actions
              </v-btn>
            </template>

            <v-list class="pa-0">
              <v-list-item v-if="canUpdateUnit" @click="submit">
                <v-list-item-title class="text-subtitle-2">
                  Save
                </v-list-item-title>
              </v-list-item>

              <v-list-item v-if="canDeleteUnit" @click="emit('delete-unit')" class="text-red">
                <v-list-item-title class="text-subtitle-2">
                  Delete Unit
                </v-list-item-title>
              </v-list-item>
            </v-list>
          </v-menu>
        </v-col>
      </v-row>
    </v-toolbar>
  </v-card>
</template>

<script setup lang="ts">
const prop = defineProps({
  site: {
    type: String,
    default: "",
  },
  roomFacility: {
    type: Object as PropType<TBuildingUnit>,
    required: true,
  },
  canUpdateUnit: {
    type: Boolean,
    default: true,
  },
  canDeleteUnit: {
    type: Boolean,
    default: true,
  }
});

const buildingUnit = ref({
  _id: "",
  site: {
    _id: "",
    name: "",
    address: {
      line1: "",
      line2: "",
      city: "",
      state: "",
      country: "",
      postalCode: "",
    },
  },
  name: "",
  owner: "",
  ownerName: "",
  building: "",
  buildingName: "",
  level: {
    _id: "",
    name: "",
  },
  // category: "",
  block: null,
  status: "active",
  buildingUnitFiles: [],
  companyName: "",
  companyRegistrationNumber: "",
  leaseStart: "",
  leaseEnd: "",
});


buildingUnit.value = JSON.parse(JSON.stringify(prop.roomFacility));

// Normalize buildingUnitFiles: extract IDs for InputFileV2, keep names in a separate map
const buildingUnitFilesNames = ref<Record<string, string>>({});
const rawFiles = buildingUnit.value.buildingUnitFiles as any[];
if (rawFiles?.length && typeof rawFiles[0] === 'object') {
  rawFiles.forEach((f: { id: string; name: string }) => {
    buildingUnitFilesNames.value[f.id] = f.name ?? "";
  });
  buildingUnit.value.buildingUnitFiles = rawFiles.map((f: { id: string }) => f.id);
}

const { getFileById } = useFile();

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

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


const ownerNameInput = ref("");
const panels = ref<string[]>(['residents']);

const tab = ref('general')

const validForm = ref(false);

const { getAll } = useBuilding();
const { getPeopleByUnit, updateById: updatePeopleById } = usePeople();
const { debounce } = useUtils();
const { searchMultipleVehiclesByUnitId, formatVehicleStatus } = useVehicle();

const loading = reactive({
  ownerProcessing: false,
})

const buildings = ref<Record<string, any>[]>([]);
const peopleItems = ref<TPeople[]>([]);
const unitVehicleItems = ref<TVehicle[]>([]);

const vehiclePage = ref(1);
const vehiclePageRange = ref("-- - -- of --");
const vehicleTotalPages = ref(0); 

const vehicleHeaders = [
  { title: "Plate Number", value: "plateNumber" },
  { title: "Owner Name", value: "name" },
  { title: "NRIC", value: "nric" },
  { title: "Type", value: "type" },
  { title: "Status", value: "status" },
];

const { data: getBuildingReq } = useLazyAsyncData(
  "get-all-buildings",
  async () => getAll({ site: prop.site, status: "active" })
);

watchEffect(() => {
  if (getBuildingReq.value) {
    buildings.value = getBuildingReq.value.items.map((building: TBuilding) => ({
      title: building.name,
      value: building._id,
      levels: building.levels,
    }));
  }
});

const { data: getUnitPeople, refresh: getUnitPeopleRefresh, pending: getUnitPeoplePending } = useLazyAsyncData(
  "get-unit-people",
  async () => await getPeopleByUnit(buildingUnit.value._id, { limit: 10, site: prop.site })
);

watch(getUnitPeople, (newData: TPeople[]) => {
  peopleItems.value = newData ?? [];
});

const { data: getUnitVehicles, refresh: getUnitVehiclesRefresh } = useLazyAsyncData(
  "get-unit-vehicles",
  async () => await searchMultipleVehiclesByUnitId({unitId: buildingUnit.value._id, page: 1, limit: 10})
);

watch(getUnitVehicles, (newData) => {
  unitVehicleItems.value = Array.isArray(newData?.items) ? newData.items : [];
  vehiclePage.value = newData?.page || 1;
  vehiclePageRange.value = newData?.pageRange || "-- - -- of --";
  vehicleTotalPages.value = newData?.totalPages || 0;
});

const unitResidentsArray = computed(() => {
  return peopleItems.value.filter((person) => person?.type === 'resident');
});

const unitTenantsArray = computed(() => {
  return peopleItems.value.filter((person) => person?.type === 'tenant');
});


// buildingUnit.value.site = prop.site;

const selectedBuilding = computed(() => {
  return buildings.value.find((b) => b.value === buildingUnit.value.building);
});

// const buildingLevels = computed(() => {
//   const levels = selectedBuilding.value?.levels ?? [];
//   return levels.map((level: { name: string; _id: string }) => ({
//     name: level.name,
//     value: level._id,
//   }))
// });

const disable = ref(false);

const { requiredRule } = useUtils();

const message = ref("");

const { updateById, categories: unitCategories } = useBuildingUnit();

function arraysAreEqual(a: any[], b: any[]): boolean {
  return a.length === b.length && a.every((val, index) => val === b[index]);
}

const hasChanges = computed(() => {
  return (
    prop.roomFacility.name !== buildingUnit.value.name ||
    // prop.roomFacility.category !== buildingUnit.value.category ||
    prop.roomFacility.level !== buildingUnit.value.level ||
    !arraysAreEqual(
      prop.roomFacility.buildingUnitFiles,
      buildingUnit.value.buildingUnitFiles
    )
  );
});

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

    if (buildingUnit.value.ownerName) {
      buildingUnit.value.owner = (buildingUnit.value.ownerName as any)._id
      buildingUnit.value.ownerName = (buildingUnit.value.ownerName as any).name
    }

    await updateById(buildingUnit.value._id ?? "", {
      name: buildingUnit.value.name,
      level: buildingUnit.value.level._id,
      // category: buildingUnit.value.category,
      buildingUnitFiles: (buildingUnit.value.buildingUnitFiles as string[] || []).map((id) => ({ id, name: buildingUnitFilesNames.value[id] ?? "" })),
      companyName: buildingUnit.value.companyName,
      companyRegistrationNumber: buildingUnit.value.companyRegistrationNumber || "",
      leaseStart: buildingUnit.value.leaseStart,
      leaseEnd: buildingUnit.value.leaseEnd,
      owner: buildingUnit.value.owner || "",
      ownerName: buildingUnit.value.ownerName || ""
    });

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


const handleUpdateOwner = async ({ person, isOwner }: { person: TPeople; isOwner: boolean }) => {
  const owners = peopleItems.value.filter(p => p.isOwner)
  message.value = ""
  // console.log('Updating owner status for', person._id, 'to', isOwner)

  const userId = person._id ?? null;

  if (!isOwner && owners.length <= 1 && owners[0]._id === person._id) {
    message.value = "There must be at least one owner for this unit."
    return
  }

  if (!userId) return message.value = "Resident user ID is missing."


  try {
    loading.ownerProcessing = true;
    await updatePeopleById(userId, { isOwner })
    getUnitPeopleRefresh();
  } catch (error: any) {
    message.value = error.response?._data?.message || "Failed to update owner status."
  } finally {
    loading.ownerProcessing = false;

  }

}

function handleUpdateVehiclePage(newPageNum: number) {
  vehiclePage.value = newPageNum;
}


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

const debounceSearchOwner = debounce(() => {
  getUnitPeopleRefresh();
}, 500);

watch(ownerNameInput, (newVal) => {
  debounceSearchOwner();
}, { immediate: false });
</script>

<style lang="scss" scoped>
.no-pointer {
  pointer-events: none;
}
</style>