<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">
          {{ props.title }}
        </span>
      </v-row>
    </v-toolbar>
    <v-card-text style="max-height: 100vh; overflow-y: auto">
      <v-form v-model="validForm" ref="form" :disabled="disable">
        <v-row no-gutters>
          <v-col cols="12" class="mt-2">
            <v-row no-gutters>
              <InputLabel class="text-capitalize" title="Email" required />
              <v-col cols="12">
                <v-text-field
                  v-model="invite.email"
                  density="comfortable"
                  :rules="[requiredRule, emailRule]"
                  :loading="loading.verifyingEmail"
                ></v-text-field>
              </v-col>
            </v-row>
          </v-col>

          <v-col
            v-if="!props.hideApp && props.adminState && APP === 'organization'"
            cols="12"
            class="mt-2"
          >
            <v-row no-gutters>
              <InputLabel class="text-capitalize" title="App" required />
              <v-col cols="12">
                <v-autocomplete
                  v-model="invite.app"
                  density="comfortable"
                  :rules="[requiredRule]"
                  :items="apps"
                  @update:model-value="handleUpdateApp"
                ></v-autocomplete>
              </v-col>
            </v-row>
          </v-col>

          <v-col cols="12">
            <v-row no-gutters>
              <InputLabel class="text-capitalize" title="Role" />
              <v-col cols="12">
                <v-autocomplete
                  v-model="invite.role"
                  :items="roles"
                  item-title="name"
                  item-value="_id"
                  :rules="[requiredRule]"
                  density="comfortable"
                ></v-autocomplete>
              </v-col>
            </v-row>
          </v-col>

          <v-col v-if="hasSite && props.adminState" cols="12">
            <v-row no-gutters>
              <InputLabel class="text-capitalize" title="Site" />
              <v-col cols="12">
                <v-autocomplete
                  v-model="invite.site"
                  :items="sites"
                  density="comfortable"
                  :rules="[requiredRule]"
                  @update:model-value="handleUpdateSite"
                ></v-autocomplete>
              </v-col>
            </v-row>
          </v-col>

          <v-col  v-if="!props.hideCreateMore"  cols="12" class="mt-2">
            <v-checkbox v-model="createMore" density="comfortable" hide-details>
              <template #label>
                <span class="text-subtitle-2 font-weight-bold">
                  Create more
                </span>
              </template>
            </v-checkbox>
          </v-col>

          <v-col cols="12" class="my-2">
            <v-row no-gutters>
              <v-col cols="12" class="text-center">
                <span
                  class="text-none text-subtitle-2 font-weight-medium text-error"
                >
                  {{ message }}
                </span>
              </v-col>
            </v-row>
          </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"
          >
            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.submittingForm"
            @click="submit"
          >
            Submit
          </v-btn>
        </v-col>
      </v-row>
    </v-toolbar>
  </v-card>
</template>

<script setup lang="ts">
import useCustomerSite from '../composables/useCustomerSite';
import useLocal from '../composables/useLocal';
import { useLocalSetup } from '../composables/useLocalSetup';
import useRole from '../composables/useRole';
import useUser from '../composables/useUser';
import useUtils from '../composables/useUtils';

const APP = useRuntimeConfig().public.APP;


const props = defineProps({
  title: {
    type: String,
    default: "Invite Form",
  },
  mode: {
    type: String,
    default: "create",
  },
  permissions: {
    type: Object,
    default: () => ({}),
  },
  app: {
    type: String,
    default: "organization",
  },
  org: {
    type: String,
    default: "",
  },
  site: {
    type: Object as PropType<TCustomerSite>,
    default: () => ({
      name: "",
      site: "",
      siteOrg: "",
      siteOrgName: "",
      org: "",
    }),
  },
  invite: {
    type: Object as PropType<TVerification>,
    default: () => ({
      email: "",
      metadata: { app: "organization", role: "" },
    }),
  },
  adminState: {
    type: Boolean,
    default: true
  },
  hideApp: {
    type: Boolean,
    default: false
  },
  inviteMember: {
  type: Boolean,
  default: false
  },
  hideCreateMore: {
  type: Boolean,
  default: false
}
});

const emit = defineEmits(["cancel", "success", "success:create-more"]);

const validForm = ref(false);
const form = ref<HTMLFormElement | null>(null);
// const app = computed(() => useRuntimeConfig().public.APP ?? "");

const loading = reactive({
  submittingForm: false,
  verifyingEmail: false,
});

const invite = ref<Record<string, any>>({
  email: "",
  app: "",
  role: "",
  org: "",
  site: "",
  siteName: "",
  isMemberInvite: false,
});

watch(
  () => [props.hideApp, props.adminState, props.app, props.org],
  () => {
    invite.value.org = props.org || ""

    if (props.hideApp) {
      invite.value.app = "property_management_agency"
      return
    }

    invite.value.app = props.adminState
      ? (props.app || "")
      : "property_management_agency"
  },
  { immediate: true }
)
// invite.value.app = props.app;
// invite.value.org = props.org ?? "";

if (props.mode === "edit") {
  invite.value.email = props.invite.email;
  invite.value.app = props.invite.metadata?.app;
  invite.value.role = props.invite.metadata?.role;
}

const { natureOfBusiness } = useLocal();
const { orgNature } = useLocalSetup();

const apps = computed(() => {
  const items = [];
  items.unshift({ title: "Organization", value: "organization" });

  const _org = "security_agency";

  if (props.app === _org || orgNature.value === _org) {
    items.push({ title: "Security Agency", value: _org });
  }

  const _cleaning = "cleaning_services";

  if (props.app === _cleaning || orgNature.value === _cleaning) {
    items.push({ title: "Cleaning Services", value: _cleaning });
  }

  const _property = "property_management_agency";

  if (props.app === _property || orgNature.value === _property) {
    items.push({ title: "Property Management Agency", value: _property });
  }

  const _mechanical = "mechanical_electrical_services";

  if (props.app === _mechanical || orgNature.value === _mechanical) {
    items.push({
      title: "Mechanical & Electrical Services",
      value: _mechanical,
    });
  }

  const _pestControl = "pest_control_services";

  if (props.app === _pestControl || orgNature.value === _pestControl) {
    items.push({
      title: "Pest Control Services",
      value: _pestControl,
    });
  }

  const _landscaping = "landscaping_services";

  if (props.app === _landscaping || orgNature.value === _landscaping) {
    items.push({
      title: "Landscaping Services",
      value: _landscaping,
    });
  }

  const _poolMaintenance = "pool_maintenance_services";

  if (props.app === _poolMaintenance || orgNature.value === _poolMaintenance) {
    items.push({
      title: "Pool Maintenance Services",
      value: _poolMaintenance,
    });
  }

  return items;
});

const hasSite = computed(() => {
  return natureOfBusiness.map((i) => i.value).includes(invite.value.app);
});

const sites = ref<Array<Record<string, any>>>([]);

const { getAll: getAllCustomerSite } = useCustomerSite();

const { data: siteData, refresh: refreshSiteData } = await useLazyAsyncData(
  "get-sites-by-org-" + props.org,
  async () => await getAllCustomerSite({ org: props.org, limit: 50 })
);

watchEffect(() => {
  if (siteData.value) {
    sites.value = siteData.value.items.map((i: any) => ({
      title: i.name,
      value: i.site,
    }));
  }
});

watchEffect(() => {
  if (hasSite.value) {
    refreshSiteData();
  }
});

const roles = ref<Array<Record<string, any>>>([]);

const { getRoles } = useRole();

const { data: RolesData, refresh: refreshRoles } = await useLazyAsyncData(
  "get-roles-by-type-" + props.org + "-" + props.app,
  () =>
  getRoles({
    org: props.org,
    type: props.app,
    limit: 50,
  }),
  { watch: [() => props.app] }
);

watchEffect(() => {
  if (RolesData.value) {
    roles.value = RolesData.value.items;
  }
});

async function handleUpdateApp(value: string)  {
  invite.value.role = "";
  invite.value.site = "";
  await refreshRoles()
}

const createMore = ref(false);
const disable = ref(false);

const { requiredRule, emailRule } = useUtils();

const message = ref("");

function resetInvite() {
  invite.value.email = "";
  invite.value.app = "organization";
  invite.value.role = "";
  message.value = "";
}

function handleUpdateSite(siteId: string) {
  const obj = sites.value.find((x) => x?.value === siteId);
  invite.value.siteName = obj?.title || "";
}

const { inviteUser, inviteMemberClient } = useUser();

async function submit() {
  loading.submittingForm = true;

  try {
    if (props.inviteMember) {
      await inviteMemberClient(invite.value);
    } else {
      await inviteUser(invite.value);
    }

    if (createMore.value) {
      form.value?.reset();
      resetInvite();
      emit("success", false);
    } else {
      emit("success", true);
    }
  } catch (error: any) {
    message.value = error.response?._data?.message || error.message;
  } finally {
    loading.submittingForm = false;
  }
}

function cancel() {
  emit("cancel");
}
</script>
