<template>
  <v-row no-gutters>
    <v-expansion-panels multiple v-model="openPanels">
      <!-- SITE SETTINGS -->
      <v-expansion-panel color="primary">
        <v-expansion-panel-title>
          <v-icon class="mr-2">mdi-cog</v-icon>
          Site Information
        </v-expansion-panel-title>

        <v-expansion-panel-text>
          <v-row no-gutters class="d-flex justify-center py-10">
            <v-form class="w-100">
              <v-row>
                <!-- Cover Photo + Preview -->
                <v-col cols="12" lg="5" class="pt-0">
                  <InputLabel
                    title="Cover Photo (displayed in resident app)"
                    class="d-block mb-2"
                  />
                  <InputFileV2
                    v-model="coverPhoto"
                    accept="image/*"
                    title="Upload cover photo"
                    :height="120"
                  />
                </v-col>
                <v-col cols="12" lg="7" class="pl-lg-4 pt-4 pt-lg-0">
                  <InputLabel title="Preview" class="d-block mb-2" />
                  <v-img
                    v-if="coverPhotoUrl"
                    :src="coverPhotoUrl"
                    aspect-ratio="16/9"
                    cover
                    rounded="lg"
                    class="w-100 border"
                  />
                  <div
                    v-else
                    class="w-100 d-flex align-center justify-center rounded-lg bg-grey-lighten-4 border border-dashed"
                    style="aspect-ratio: 16/9"
                  >
                    <span class="text-caption text-medium-emphasis"
                      >No cover photo uploaded</span
                    >
                  </div>
                </v-col>

                <!-- Description + Site Documents -->
                <v-col cols="12" lg="6" class="mt-2">
                  <InputLabel title="Description" class="d-block mb-1" />
                  <v-textarea
                    v-model="description"
                    variant="outlined"
                    density="compact"
                    rows="4"
                    hide-details
                    no-resize
                    style="height: 119px"
                  />
                </v-col>
                <v-col cols="12" lg="6" class="mt-2 pl-lg-2">
                  <InputLabel title="Site Documents" class="d-block mb-1" />
                  <InputFileV2
                    v-model="siteDocuments"
                    :multiple="true"
                    accept="*/*"
                    title="Upload documents"
                    :height="104"
                  />
                </v-col>

                <!-- Submit -->
                <v-col cols="12" class="pt-0 d-flex justify-end">
                  <v-btn
                    color="primary-button"
                    class="text-none"
                    size="large"
                    variant="flat"
                    text="Save"
                    :loading="savingSiteInfo"
                    @click="saveSiteInfo"
                  />
                </v-col>

                <!-- Divider -->
                <v-col cols="12" class="my-2">
                  <v-divider />
                </v-col>

                <v-col cols="12">
                  <v-row no-gutters>
                    <v-col cols="12" lg="4" class="mt-2">
                      <NumberSettingField
                        v-model="blocks"
                        title="No. of blocks"
                        type="blocks"
                        :site-id="siteId"
                        :disabled="existingBlockNumber === blocks"
                        @success="refreshSiteData"
                      />
                    </v-col>
                  </v-row>
                </v-col>

                <v-col cols="12">
                  <v-row no-gutters>
                    <v-col cols="12" lg="4" class="mt-2">
                      <NumberSettingField
                        v-model="guardPosts"
                        title="No. of guard posts"
                        type="guard_posts"
                        :site-id="siteId"
                        :disabled="existingGuardPostNumber === guardPosts"
                        @success="refreshSiteData"
                      />
                    </v-col>
                  </v-row>
                </v-col>
              </v-row>
            </v-form>
          </v-row>
        </v-expansion-panel-text>
      </v-expansion-panel>

      <!-- ANPR CAMERA -->
      <v-expansion-panel v-if="showAnprCamera" color="primary">
        <v-expansion-panel-title>
          <v-icon class="mr-2">mdi-camera</v-icon>
          ANPR Camera
        </v-expansion-panel-title>

        <v-expansion-panel-text>
          <v-container fluid class="px-0">
            <v-row dense>
              <v-col cols="6">
                <v-switch
                  v-model="ANPRSwitches.enableUnregistered"
                  :disabled="!canManageSiteSettings"
                  label="Enable Unregistered Vehicles"
                  color="primary"
                  hide-details
                ></v-switch>
              </v-col>

              <v-col cols="6">
                <v-switch
                  v-model="ANPRSwitches.openBarrierPickUpDropOff"
                  :disabled="!canManageSiteSettings"
                  label="Open Barrier for Pick-up and Drop-off"
                  color="primary"
                  hide-details
                ></v-switch>
              </v-col>

              <v-col cols="6">
                <v-switch
                  v-model="ANPRSwitches.vehicleSnapshot"
                  :disabled="!canManageSiteSettings"
                  label="Capture Vehicle Snapshot"
                  color="primary"
                  hide-details
                ></v-switch>
              </v-col>
            </v-row>

            <v-row v-if="canManageSiteSettings">
              <v-col cols="auto">
                <v-btn
                  variant="flat"
                  color="primary"
                  class="text-none"
                  :loading="isSaving"
                  @click="saveANPRSettings"
                >
                  Save
                </v-btn>
              </v-col>
            </v-row>
          </v-container>

          <v-divider class="my-4"></v-divider>

          <CameraMain
            :site="siteId"
            :read-only="!canManageSiteSettings"
            :guard-posts="siteData?.metadata?.guardPosts"
          />
        </v-expansion-panel-text>
      </v-expansion-panel>

      <!-- CCTV CAMERA -->
      <v-expansion-panel v-if="showCctvCamera" color="primary">
        <v-expansion-panel-title>
          <v-icon class="mr-2">mdi-cctv</v-icon>
          CCTV Camera
        </v-expansion-panel-title>

        <v-expansion-panel-text>
          <CameraMain
            :site="siteId"
            type="ip"
            :read-only="!canManageSiteSettings"
          />
        </v-expansion-panel-text>
      </v-expansion-panel>

      <v-expansion-panel v-if="showDeliveryCompanies" color="primary">
        <v-expansion-panel-title>
          <v-icon class="mr-2">mdi-truck</v-icon>
          Delivery Companies
        </v-expansion-panel-title>
        <v-expansion-panel-text class="">
          <DeliveryCompany
            :site="siteId"
            v-model:initial="deliveryCompanies"
            @refresh-site="refreshSiteData"
            @update:companiesValue="handleUpdateCompanies"
            :read-only="!canManageSiteSettings"
          />
        </v-expansion-panel-text>
      </v-expansion-panel>

      <v-expansion-panel v-if="showResidentVisitors" color="primary">
        <v-expansion-panel-title>
          <v-icon class="mr-2">mdi-car</v-icon>
          Resident Visitors
        </v-expansion-panel-title>
        <v-expansion-panel-text>
          <OvernightParkingAvailability :site="siteId" />
        </v-expansion-panel-text>
      </v-expansion-panel>

      <slot
        name="panels"
        :can-manage="canManageSiteSettings"
        :site-id="siteId"
      />
    </v-expansion-panels>

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

<script setup lang="ts">
import useFile from "../composables/useFile";
import useSiteSettings from "../composables/useSiteSettings";
import useUtils from "../composables/useUtils";
import useANPRSettings from "../composables/useANPRSettings";

const props = defineProps({
  siteId: { type: String, required: true },
  createdBy: { type: String },
  canManageSiteSettings: { type: Boolean, default: false },
  showAnprCamera: { type: Boolean, default: false },
  showCctvCamera: { type: Boolean, default: false },
  showDeliveryCompanies: { type: Boolean, default: false },
  showResidentVisitors: { type: Boolean, default: false },
});

const openPanels = ref([]); // default open first

const { getSiteById, updateSitebyId, updateSiteInformation } =
  useSiteSettings();
const { requiredRule } = useUtils();
const { getFileUrl } = useFile();

const blocks = ref(0);
const guardPosts = ref(0);
const gracePeriod = ref(0);

const existingBlockNumber = ref(0);
const existingGuardPostNumber = ref(0);
const existingGracePeriodNumber = ref(0);

const gracePeriodValid = ref(false);
const gracePeriodLoading = ref(false);
const deliveryCompanies = ref<string[]>([]);

const siteLogo = ref<any[]>([]);
const uploadedSiteLogo = ref("");

const coverPhoto = ref<string[]>([]);
const description = ref<string>("");
const siteDocuments = ref<string[]>([]);
const siteDocumentsNames = ref<Record<string, string>>({});
const savingSiteInfo = ref<boolean>(false);

const coverPhotoUrl = computed(() =>
  coverPhoto.value.length > 0 ? getFileUrl(coverPhoto.value[0]) : ""
);

const toast = reactive({
  show: false,
  message: "",
  color: "",
});

function showSnackbar(text: string, color = "success") {
  toast.message = text;
  toast.color = color;
  toast.show = true;
}

const { data: siteData, refresh: refreshSiteData } = await useLazyAsyncData(
  `site-${props.siteId}`,
  () => getSiteById(props.siteId)
);

watch(
  siteData,
  (val: TSite) => {
    const siteDataValue = val as any;
    if (siteDataValue) {
      blocks.value = siteDataValue.metadata?.block || 0;
      existingBlockNumber.value = blocks.value;

      guardPosts.value = siteDataValue.metadata?.guardPosts || 0;
      existingGuardPostNumber.value = guardPosts.value;
      deliveryCompanies.value = Array.isArray(
        siteDataValue?.deliveryCompanyList
      )
        ? [...siteDataValue.deliveryCompanyList]
        : [];

      const info = siteDataValue.siteInformation;
      if (info) {
        coverPhoto.value = info.bgImage ? [info.bgImage] : [];
        description.value = info.description ?? "";
        const docs: { id: string; name: string }[] = info.docs ?? [];
        siteDocuments.value = docs.map((d) => d.id);
        docs.forEach((d) => {
          siteDocumentsNames.value[d.id] = d.name;
        });
      }
    }
  },
  { immediate: true }
);

async function handleSaveGracePeriod() {
  gracePeriodLoading.value = true;
  try {
    await updateSitebyId(props.siteId, {
      field: "metadata.gracePeriod",
      value: gracePeriod.value,
    });
    show("Grace period updated", "success");
    refreshSiteData();
  } catch (e: any) {
    show(e?.data?.message || "Error updating grace period", "error");
  } finally {
    gracePeriodLoading.value = false;
  }
}

async function saveSiteInfo() {
  savingSiteInfo.value = true;
  try {
    await updateSiteInformation(props.siteId, {
      bgImage: coverPhoto.value[0] ?? "",
      description: description.value,
      docs: siteDocuments.value.map((id) => ({
        id,
        name: siteDocumentsNames.value[id] ?? "",
      })),
    });
    showSnackbar("Site information updated successfully.");
  } catch (err: any) {
    const msg =
      err?.response?._data?.message ??
      err?.message ??
      "Failed to update site information.";
    showSnackbar(msg, "error");
  } finally {
    savingSiteInfo.value = false;
  }
}

async function handleLogo(action: string) {
  try {
    await updateSitebyId(props.siteId, {
      field: "metadata.incidentLogo",
      value: action === "add" ? siteLogo.value[0] : 0,
    });
    show("Logo updated", "success");
    refreshSiteData();
  } catch {
    show("Error updating logo", "error");
  } finally {
    siteLogo.value = [];
  }
}

const onUploadedLogoPreview = () => {
  if (!uploadedSiteLogo.value) return "";
  return getFileUrl(uploadedSiteLogo.value);
};

function handleUpdateCompanies(value: string[]) {
  deliveryCompanies.value = value;
}

const route = useRoute();

function show(message: string, color: string) {
  toast.show = true;
  toast.message = message;
  toast.color = color;
}

// ANPR Settings
const { getANPRSettingBySite, createUpdateANPRSettings } = useANPRSettings();
const isSaving = ref(false);

// Reactive object to hold the state of the 3 switches
const ANPRSwitches = ref({
  enableUnregistered: false,
  openBarrierPickUpDropOff: false,
  vehicleSnapshot: false,
});

await useLazyAsyncData(`anpr-settings-${props.siteId}`, async () => {
  const data = await getANPRSettingBySite({
    site: props.siteId,
    userType: "site",
  });
  console.log("data", data);
  if (typeof data?.ANPRSwitches == "object") {
    ANPRSwitches.value = data?.ANPRSwitches;
  }
});

const saveANPRSettings = async () => {
  try {
    isSaving.value = true;

    // Replace this with your actual API endpoint / store action
    // await $fetch(`/api/sites/${siteId.value}/camera-settings`, {
    //   method: 'POST',
    //   body: cameraSettings.value
    // })
    const data = {
      site: props.siteId,
      ANPRSwitches: ANPRSwitches.value,
      updatedBy: props.createdBy,
      userType: "site",
    };
    console.log("saveANPRSettings data:", data);
    await createUpdateANPRSettings(data);
    show("Saved successfully", "success");
  } catch (error) {
    console.error("Failed to save settings:", error);
  } finally {
    isSaving.value = false;
  }
};
</script>
