<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">Replace Access Card</span>
      </v-row>
    </v-toolbar>
    <v-card-text style="max-height: 100vh; overflow-y: auto" class="pa-0">
      <v-form v-model="validForm" :disabled="loading">
        <v-row no-gutters class="px-6 pt-4 pb-6">
          <!-- Card being replaced -->
          <v-col cols="12" class="px-1 mb-4">
            <div class="text-caption text-grey mb-1 font-weight-bold">
              Card being replaced
            </div>
            <v-chip size="small" variant="tonal" color="warning">
              {{ card.cardNo }}
            </v-chip>
          </v-col>

          <!-- Replacement card -->
          <v-col cols="12" class="px-1">
            <InputLabel
              class="text-capitalize font-weight-bold"
              title="Replacement Card"
              required
            />
            <v-autocomplete
              v-model="form.replacementCardId"
              density="compact"
              :items="replacementOptions"
              hide-details="auto"
              item-title="cardNo"
              item-value="_id"
              placeholder="Select replacement card..."
              persistent-placeholder
              :rules="[requiredRule]"
              :no-data-text="noDataText"
            />
          </v-col>

          <!-- Remarks -->
          <v-col cols="12" class="px-1 mt-2">
            <InputLabel
              class="text-capitalize font-weight-bold"
              title="Remarks"
              required
            />
            <v-textarea
              v-model="form.remarks"
              density="compact"
              hide-details="auto"
              placeholder="Enter remarks..."
              persistent-placeholder
              rows="3"
              auto-grow
              :rules="[requiredRule]"
            />
          </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="cancel"
            :disabled="loading"
          >
            Cancel
          </v-btn>
        </v-col>
        <v-col cols="6">
          <v-btn
            tile
            block
            variant="flat"
            color="black"
            class="text-none"
            size="48"
            :disabled="!validForm || loading"
            :loading="loading"
            @click="submit"
          >
            Replace
          </v-btn>
        </v-col>
      </v-row>
    </v-toolbar>
  </v-card>
</template>
<script setup lang="ts">
const props = defineProps({
  card: {
    type: Object as PropType<Record<string, any>>,
    required: true,
  },
  unit: {
    type: Object as PropType<Record<string, any>>,
    required: true,
  },
  siteId: {
    type: String,
    default: "",
  },
});
const emit = defineEmits(["cancel", "success", "error"]);

const { requiredRule } = useUtils();

const validForm = ref(false);
const loading = ref(false);

const form = ref({
  replacementCardId: null as string | null,
  remarks: "",
});

const cardType = computed(() => {
  const id = props.card._id;
  if (props.unit.available?.physical?.some((c: any) => c._id === id)) return "physical";
  if (props.unit.assigned?.physical?.some((c: any) => c._id === id)) return "physical";
  if (props.unit.available?.non_physical?.some((c: any) => c._id === id)) return "non_physical";
  if (props.unit.assigned?.non_physical?.some((c: any) => c._id === id)) return "non_physical";
  return null;
});

const replacementOptions = computed(() => {
  const id = props.card._id;
  if (cardType.value === "physical") {
    return (props.unit.available?.physical ?? []).filter((c: any) => c._id !== id);
  }
  if (cardType.value === "non_physical") {
    return (props.unit.available?.non_physical ?? []).filter((c: any) => c._id !== id);
  }
  return [];
});

const noDataText = computed(() => {
  if (!cardType.value) return "Unable to determine card type";
  const label = cardType.value === "physical" ? "physical" : "non-physical";
  return `No available ${label} cards for replacement`;
});

function cancel() {
  emit("cancel");
}

async function submit() {
  loading.value = true;
  try {
    const { replaceCard } = useCard();
    const { currentUser } = useLocalAuth();
    // @TODO: userId should be the ID of the unit owner, not the current user
    await replaceCard({
      cardId: props.card._id,
      issuedCardId: form.value.replacementCardId!,
      unitId: props.unit._id,
      remarks: form.value.remarks,
      userId: currentUser.value?._id ?? "",
    });
    emit("success");
  } catch (error: any) {
    const msg =
      error?.response?._data?.message ||
      error?.data?.message ||
      "Failed to replace access card.";
    emit("error", msg);
  } finally {
    loading.value = false;
  }
}
</script>
