<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">
          {{ title }}
        </span>
      </v-row>
    </v-toolbar>

    <v-card-text style="max-height: 100vh; overflow-y: auto" class="pa-5 my-5">
      <v-form ref="formRef" v-model="validForm" :disabled="disable">
        <v-row no-gutters class="pt-4">
          <v-col v-if="isCCTV" cols="12">
            <InputLabel class="text-capitalize" title="Camera Name" required />
            <v-text-field
              v-model.trim="camera.name"
              density="comfortable"
              :rules="[requiredRule]"
              placeholder="Enter CCTV camera name"
            />
          </v-col>
          <v-col cols="12">
            <InputLabel class="text-capitalize" title="URL" required />
            <v-text-field
              v-model.trim="camera.host"
              density="comfortable"
              :rules="[requiredRule, hostRule]"
              placeholder="Enter camera URL"
            />
          </v-col>

          <!-- <v-col v-if="isANPR" cols="12">
            <InputLabel class="text-capitalize" title="Category" required />
            <v-select
              v-model="camera.category"
              :items="anprCategoryOptions"
              density="comfortable"
              :rules="[requiredRule]"
            />
          </v-col> -->

          <v-col v-if="isANPR" cols="12">
            <InputLabel class="text-capitalize" title="Type" required />
            <v-select
              v-model="camera.direction"
              :items="anprDirectionOptions"
              density="comfortable"
              :rules="[requiredRule]"
            />
          </v-col>

          <!-- <v-col v-if="isANPR" cols="12">
            <InputLabel class="text-capitalize" title="Guard House" />
            <v-select
              v-model="camera.guardPost"
              :items="guardPostOptions"
              density="comfortable"
            />
          </v-col> -->

          <v-col v-if="isANPR" cols="12">
            <InputLabel class="text-capitalize" title="User" required />
            <v-text-field
              v-model.trim="camera.username"
              density="comfortable"
              :rules="[requiredRule]"
              placeholder="Enter username"
            />
          </v-col>

          <v-col v-if="isANPR" cols="12">
            <InputLabel class="text-capitalize" title="Password" required />
            <v-text-field
              v-model.trim="camera.password"
              type="password"
              density="comfortable"
              :rules="[requiredRule]"
              placeholder="Enter password"
            />
          </v-col>

          <v-col v-if="isANPR" cols="12">
            <InputLabel class="text-capitalize" title="Status" />
            <v-switch
              v-model="camera.status"
              hide-details
              inset
              density="comfortable"
              true-value="active"
              false-value="inactive"
              :color="camera.status === 'active' ? 'success' : 'grey'"
              :label="camera.status === 'active' ? 'Active' : 'Inactive'"
            ></v-switch>
          </v-col>
        </v-row>
      </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="back"
            text="Cancel"
          />
        </v-col>
        <v-col cols="6">
          <v-btn
            tile
            block
            variant="flat"
            color="black"
            class="text-none"
            size="48"
            :disabled="!validForm || disable || !hasChanges"
            @click="submit"
            :loading="disable"
            text="Submit"
          />
        </v-col>
      </v-row>
    </v-toolbar>
  </v-card>
</template>

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

const prop = defineProps({
  title: {
    type: String,
    default: "Site Camera Form",
  },
  site: {
    type: String,
    required: true,
  },
  guardPosts: {
    type: Number,
    default: 0,
  },
  type: {
    type: String as PropType<TSiteCamera["type"]>,
    default: "anpr",
  },
  mode: {
    type: String,
    default: "add",
  },
  camera: {
    type: Object as PropType<TSiteCamera>,
    default: () => ({
      site: "",
      host: "",
      username: "",
      password: "",
      type: "ip",
      category: "standard",
      direction: "both",
      guardPost: null,
      status: "active",
      name: "",
    }),
  },
});

const { requiredRule, isValidBaseURL } = useUtils();
const emit = defineEmits(["cancel", "select", "success", "error"]);

const hostRule = computed(() => {
  return (v: string | any) => {
    if (!v) return true;

    const isAnpr = prop.type === "anpr";

    const anprRegex = /^http:\/\/[a-z0-9.-]+\.[a-z]{2,}(:\d+)?$/i;
    const defaultRegex = /^https:\/\/[a-z0-9.-]+\.[a-z]{2,}\/[a-z0-9._-]+$/i;

    if (isAnpr) {
      return anprRegex.test(v) || "Format: http://domain:port";
    }

    return defaultRegex.test(v) || "Format: https://domain/path";
  };
});

const camera = ref<TSiteCamera>({
  site: "",
  host: "",
  username: "",
  password: "",
  type: "ip",
  category: "standard",
  direction: "both",
  name: "",
  guardPost: null,
  status: "active",
});

camera.value.site = prop.site;

if (prop.mode === "edit") {
  camera.value = JSON.parse(JSON.stringify(prop.camera));
}
console.log("prop.camera", prop?.camera);
camera.value.site = prop.site;
camera.value.type = prop.type;
camera.value.category =
  prop.camera?.category && prop.title == "Edit Camera"
    ? prop.camera?.category
    : prop.type == "anpr"
    ? "resident"
    : "standard";
camera.value.direction =
  prop.camera?.direction && prop.title == "Edit Camera"
    ? prop.camera?.direction
    : prop.type == "anpr"
    ? "both"
    : "none";

const validForm = ref(false);
const formRef = ref<HTMLFormElement | null>(null);
const disable = ref(false);
const message = ref("");

const isANPR = computed(() => prop.type === "anpr");
const isCCTV = computed(() => prop.type === "ip");

const anprCategoryOptions = computed(() => [
  { title: "Resident", value: "resident" },
  { title: "Visitor", value: "visitor" },
]);

const anprDirectionOptions = computed(() => [
  { title: "Entry", value: "entry" },
  { title: "Exit", value: "exit" },
  { title: "Both Entry and Exit", value: "both" },
  { title: "Visitors", value: "visitors" },
  { title: "Residents", value: "residents" },
]);

function back() {
  message.value = "";

  if (formRef.value) {
    formRef.value.reset();
  }

  emit("cancel");
}

const hasChanges = computed(() => {
  // Only check for changes in edit mode
  if (prop.mode === "edit") {
    return (
      camera.value.host !== prop.camera.host ||
      camera.value.username !== prop.camera.username ||
      camera.value.password !== prop.camera.password ||
      camera.value.category !== prop.camera.category ||
      camera.value.guardPost !== prop.camera.guardPost ||
      camera.value.direction !== prop.camera.direction ||
      camera.value.name !== prop.camera.name
    );
  }

  // For add mode, always return true (allow submission)
  return true;
});

const { addCamera, updateSiteCamera } = useSiteSettings();

async function submit() {
  disable.value = true;
  camera.value.guardPost = camera.value.guardPost ?? 0;

  try {
    if (prop.mode === "add") {
      await addCamera(camera.value);
    }

    if (prop.mode === "edit") {
      await updateSiteCamera(camera.value._id ?? "", {
        host: camera.value.host,
        username: camera.value.username,
        password: camera.value.password,
        category: camera.value.category,
        guardPost: camera.value.guardPost,
        direction: camera.value.direction,
        status: camera.value.status,
        name: camera.value.name,
      });
    }

    emit("success", `${prop.title} added successfully!`);
  } catch (error: any) {
    console.log(
      "error",
      error.response?._data?.message || "Failed to add camera"
    );
    emit("error", error.response?._data?.message || "Failed to add camera");
  } finally {
    disable.value = false;
  }
}

const guardPostOptions = computed(() => {
  const items = [];

  for (let index = 0; index < prop.guardPosts; index++) {
    items.push({
      title: `Guard House ${index + 1}`,
      value: index + 1,
    });
  }

  return items;
});
</script>
<style scoped></style>
