<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 px-7"
    >
      <v-form ref="formRef" v-model="valid" @submit.prevent="submit">
        <v-row no-gutters>
          <v-col cols="12" class="mb-4">
            <label class="text-subtitle-2 font-weight-medium mb-2">
              Name <span class="text-red">*</span>
            </label>
            <v-text-field
              v-model="form.name"
              placeholder="Enter name"
              variant="outlined"
              density="comfortable"
              :rules="[rules.required]"
              hide-details="auto"
            />
          </v-col>

          <v-col cols="12" class="mb-4">
            <label class="text-subtitle-2 font-weight-medium mb-2">
              Tag ID <span class="text-red">*</span>
            </label>
            <v-text-field
              v-model="form.tagID"
              placeholder="Enter tag id"
              variant="outlined"
              density="comfortable"
              :rules="[rules.required, rules.noSpaces]"
              hide-details="auto"
              @input="handleTagIDInput"
            />
          </v-col>

        </v-row>
      </v-form>
    </v-card-text>

    <v-toolbar class="pa-0" density="compact">
      <v-row no-gutters>
        <v-col cols="6" class="pa-0">
          <v-btn
            block
            variant="text"
            class="text-none"
            size="large"
            @click="$emit('cancel')"
            height="48"
            :disabled="loading"
          >
            Cancel
          </v-btn>
        </v-col>

        <v-col cols="6" class="pa-0">
          <v-btn
            block
            tile
            variant="flat"
            class="text-none"
            size="large"
            height="48"
            color="black"
            @click="submit"
            :loading="loading"
            :disabled="!valid || loading || !hasChanges"
          >
            Submit
          </v-btn>
        </v-col>
      </v-row>
    </v-toolbar>
  </v-card>
</template>

<script setup lang="ts">

import useNFCPatrolTag from "../../composables/useNFCPatrolTag";

const props = defineProps({
  title: {
    type: String,
    default: "Add NFC Tag",
  },
  site: {
    type: String,
    required: true,
  },
  orgId: {
    type: String,
    required: true,
  },
  mode: {
    type: String as PropType<"create" | "edit">,
    default: "create",
  },
  nfcTag: {
    type: Object as PropType<any>,
    default: () => ({
      name: "",
      tagID: "",
      status: "active",
    }),
  },
});

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

const formRef = ref();
const valid = ref(false);
const loading = ref(false);

const form = ref({
  name: "",
  tagID: "",
  status: "active",
});


const originalForm = ref({
  name: "",
  tagID: "",
  status: "active",
});

const statusOptions = [
  { title: "Active", value: "active" },
  { title: "Inactive", value: "inactive" },
];

const rules = {
  required: (v: any) => !!v || "This field is required",
  noSpaces: (v: any) => !/\s/.test(v) || "Spaces are not allowed",
};

const hasChanges = computed(() => {
  if (props.mode === "create") {
  
    return true;
  }
  

  return (
    form.value.name !== originalForm.value.name ||
    form.value.tagID !== originalForm.value.tagID ||
    form.value.status !== originalForm.value.status
  );
});


watchEffect(() => {
  if (props.mode === "edit" && props.nfcTag) {
    form.value = {
      name: props.nfcTag.name || "",
      tagID: props.nfcTag.tagID || "",
      status: props.nfcTag.status || "active",
    };
   
    originalForm.value = {
      name: props.nfcTag.name || "",
      tagID: props.nfcTag.tagID || "",
      status: props.nfcTag.status || "active",
    };
  }
});

const { add: addNFCTag, updateById: updateNFCTag } = useNFCPatrolTag();

function handleTagIDInput(event: any) {

  const value = event.target.value;
  form.value.tagID = value.toUpperCase().replace(/\s/g, "");
}

async function submit() {
  const { valid: isValid } = await formRef.value.validate();

  if (!isValid) return;
  
  
  if (props.mode === "edit" && !hasChanges.value) {
    return;
  }

  loading.value = true;

  try {
    
    const payload: any = {
      site: props.site,
      tagID: form.value.tagID,
      name: form.value.name,
    };
    
  
    if (props.mode === "edit") {
      payload._id = props.nfcTag._id;
      payload.updateType = "Edit";
    }

    if (props.mode === "create") {
      await addNFCTag(payload);
    } else {
      await updateNFCTag(props.nfcTag._id, payload);
    }

    emit("success");


    if (props.mode === "create") {
      form.value = {
        name: "",
        tagID: "",
        status: "active",
      };
      formRef.value.reset();
    }
  } catch (error: any) {
    console.error("Error submitting NFC tag:", error);
    emit("error", error);
  } finally {
    loading.value = false;
  }
}
</script>
