<template>
  <v-dialog v-model="showDialog" max-width="450">
    <v-card>
      <v-toolbar>
        <template v-if="$slots.header">
          <slot
            name="header"
            :title="
              prop.mode === 'edit'
                ? `Edit ${prop.entityType}`
                : `Add New ${prop.entityType}`
            "
            :close="close"
          />
        </template>
        <template v-else>
          <v-row no-gutters class="fill-height px-6" align="center">
            <span class="font-weight-bold text-h6 text-capitalize">{{
              prop.mode === "edit"
                ? `Edit ${prop.entityType}`
                : `Add New ${prop.entityType}`
            }}</span>
          </v-row>
        </template>
      </v-toolbar>

      <v-card-text class="pa-4">
        <v-form ref="formRef" v-model="valid">
          <v-row no-gutters class="pa-0">
            <v-col v-if="prop.showType" cols="12" class="pa-0 mb-2">
              <InputLabel for="type" title="Type" required class="mb-1" />
              <v-select
                v-model="typeModel"
                :items="typeOptions"
                density="comfortable"
                variant="outlined"
                hide-details
                class="w-100 mb-0"
              />
            </v-col>

            <v-col cols="12" class="pa-0 mb-0">
              <InputLabel
                for="name"
                :title="prop.label"
                required
                class="mb-1"
              />
              <v-text-field
                v-model="model"
                :rules="[requiredRule]"
                class="mb-0"
              />
            </v-col>

            <v-col v-if="prop.showUnits" cols="12" class="pa-0 mb-2">
              <InputLabel for="units" title="Units" class="mb-1" />
              <v-autocomplete
                v-model="unitsModel"
                :items="unitItems"
                :loading="loadingUnits"
                item-title="title"
                item-value="value"
                density="comfortable"
                variant="outlined"
                :rules="[unitsRequiredRule]"
                multiple
                chips
                closable-chips
                placeholder="Select units"
                class="mb-0"
              />
            </v-col>

            <v-col v-if="prop.showOptional" cols="12" class="mb-4">
              <v-row dense justify="center">
                <v-col cols="6" class="pa-0">
                  <v-btn
                    block
                    color="primary"
                    variant="text"
                    class="text-none font-weight-bold"
                    text="Optional"
                    @click="show = !show"
                  ></v-btn>
                </v-col>
              </v-row>
            </v-col>

            <v-expand-transition v-if="prop.showOptional">
              <v-row v-show="show" no-gutters>
                <v-col cols="12">
                  <v-row no-gutters>
                    <InputLabel
                      class="text-capitalize font-weight-bold"
                      title="Number of visits"
                    />
                    <v-col cols="12">
                      <v-text-field
                        v-model="set"
                        density="comfortable"
                        type="number"
                        min="1"
                      ></v-text-field>
                    </v-col>
                  </v-row>
                </v-col>
              </v-row>
            </v-expand-transition>
          </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="close"
              height="48"
            >
              Cancel
            </v-btn>
          </v-col>

          <v-col cols="6" class="pa-0">
            <v-btn
              block
              variant="flat"
              color="black"
              class="text-none font-weight-bold rounded-0"
              height="48"
              :loading="submitting"
              @click="submit"
            >
              {{ prop.mode === "edit" ? "Save" : "Create" }}
            </v-btn>
          </v-col>
        </v-row>
      </v-toolbar>
    </v-card>
  </v-dialog>
</template>

<script setup lang="ts">
import useUnits from '../composables/useUnits';
import useUtils from '../composables/useUtils';

const model = defineModel("name", { type: String, default: "" });
const typeModel = defineModel("type", { type: String, default: "Common" });
const set = defineModel("set", { type: Number, default: 1 });
const unitsModel = defineModel("units", { type: Array, default: () => [] });
const showDialog = defineModel({ type: Boolean, default: false });

const prop = defineProps({
  mode: {
    type: String,
    default: "add",
  },
  areaData: {
    type: Object,
    default: null,
  },
  label: { type: String, default: "Name" },
  entityType: { type: String, default: "Area" }, // values: "Area", "Unit"
  showType: { type: Boolean, default: true },
  showOptional: { type: Boolean, default: true },
  showUnits: { type: Boolean, default: false },
  site: { type: String, default: "" },
  serviceType: { type: String, default: "" },
});

const emit = defineEmits(["saved", "close"]);

const formRef = ref<any>(null);
const valid = ref(false);
const submitting = ref(false);
const show = ref(false);

const { requiredRule } = useUtils();

const unitsRequiredRule = (v: any) => {
  if (Array.isArray(v)) return v.length > 0 || "Select at least one unit";
  return !!v || "Select at least one unit";
};

const typeOptions = ["Common", "Toilet"];

const unitItems = ref<Array<{ title: string; value: string }>>([]);
const loadingUnits = ref(false);

const { getUnits } = useUnits();

watch(
  [showDialog, () => prop.showUnits, () => prop.site],
  async ([isOpen, shouldShow, siteId]) => {
    if (isOpen && shouldShow && siteId) {
      loadingUnits.value = true;
      try {
        const response = await getUnits({ site: siteId, limit: 100, serviceType: prop.serviceType });
        unitItems.value = (response?.items || []).map((unit: any) => ({
          title: unit.name,
          value: unit._id || unit.id,
        }));
      } catch (error) {
        console.error("Error loading units:", error);
      } finally {
        loadingUnits.value = false;
      }
    }
  }
);

watchEffect(() => {
  model.value = prop.areaData?.name || "";
  typeModel.value = prop.areaData?.type || "Common";
  set.value = prop.areaData?.set || 1;
  unitsModel.value =
    prop.areaData?.units?.map((u: any) => u.unit || u._id || u.id || u) || [];
});

function close() {
  showDialog.value = false;
  emit("close");
}

async function submit() {
  const form = formRef.value as any;
  let ok = valid.value;
  if (form && typeof form.validate === "function") {
    try {
      ok = await form.validate();
    } catch (e) {
      ok = false;
    }
  }

  if (!ok) return;

  submitting.value = true;
  try {
    await new Promise((r) => setTimeout(r, 500));

    if (prop.showType) {
      emit("saved", {
        name: model.value,
        type: typeModel.value,
        set: set.value,
        units: prop.showUnits ? unitsModel.value : undefined,
      });
    } else {
      emit("saved", model.value);
    }

    model.value = "";
    typeModel.value = "Common";
    set.value = 1;
    unitsModel.value = [];

    showDialog.value = false;
    emit("close");
  } catch (e) {
  } finally {
    submitting.value = false;
  }
}
</script>
