<template>
    <a-drawer
        :title="pageTitle"
        :width="drawerWidth"
        :open="visible"
        :body-style="{ paddingBottom: '80px' }"
        :footer-style="{ textAlign: 'right' }"
        :maskClosable="false"
        @close="onClose"
    >
        <a-form layout="vertical">
            <a-row>
                <a-col :xs="24" :sm="24" :md="6" :lg="6">
                    <a-form-item
                        :label="$t('staff_member.profile_image')"
                        name="profile_image"
                        :help="rules.profile_image ? rules.profile_image.message : null"
                        :validateStatus="rules.profile_image ? 'error' : null"
                    >
                        <ImageUpload
                            :formData="newFormData"
                            imageField="profile_image"
                            @onFileSelected="
                                (file) => {
                                    newFormData.profile_image = file;
                                }
                            "
                        />
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="18" :lg="18">
                    <a-row :gutter="16">
                        <a-col :xs="24" :sm="24" :md="12" :lg="12">
                            <a-form-item
                                :label="$t('staff_member.name')"
                                name="name"
                                :help="rules.name ? rules.name.message : null"
                                :validateStatus="rules.name ? 'error' : null"
                                class="required"
                            >
                                <a-input
                                    v-model:value="newFormData.name"
                                    :placeholder="
                                        $t('common.placeholder_default_text', [
                                            $t('staff_member.name'),
                                        ])
                                    "
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :xs="24" :sm="24" :md="12" :lg="12">
                            <a-form-item
                                :label="$t('staff_member.email')"
                                name="email"
                                :help="rules.email ? rules.email.message : null"
                                :validateStatus="rules.email ? 'error' : null"
                                class="required"
                            >
                                <a-input
                                    v-model:value="newFormData.email"
                                    :placeholder="
                                        $t('common.placeholder_default_text', [
                                            $t('staff_member.email'),
                                        ])
                                    "
                                />
                            </a-form-item>
                        </a-col>
                    </a-row>
                    <a-row :gutter="16">
                        <a-col :xs="24" :sm="24" :md="24" :lg="24">
                            <a-form-item
                                :label="$t('staff_member.phone')"
                                name="phone"
                                :help="rules.phone ? rules.phone.message : null"
                                :validateStatus="rules.phone ? 'error' : null"
                            >
                                <PhoneInput
                                    v-model="newFormData.phone"
                                    :placeholder="
                                        $t('common.placeholder_default_text', [
                                            $t('staff_member.phone'),
                                        ])
                                    "
                                />
                            </a-form-item>
                        </a-col>
                    </a-row>
                    <a-row
                        v-if="permsArray.includes('assign_role') || permsArray.includes('admin')"
                        :gutter="16"
                    >
                        <a-col :xs="24" :sm="24" :md="12" :lg="12">
                            <a-form-item
                                :label="$t('staff_member.allow_login')"
                                name="allow_login"
                                :help="
                                    rules.allow_login ? rules.allow_login.message : null
                                "
                                :validateStatus="rules.allow_login ? 'error' : null"
                            >
                                <a-switch
                                    v-model:checked="newFormData.allow_login"
                                    :checkedValue="1"
                                    :unCheckedValue="0"
                                />
                            </a-form-item>
                        </a-col>
                        <a-col
                            v-if="newFormData.allow_login"
                            :xs="24"
                            :sm="24"
                            :md="12"
                            :lg="12"
                        >
                            <a-form-item
                                :label="$t('staff_member.role')"
                                name="role_id"
                                :help="rules.role_id ? rules.role_id.message : null"
                                :validateStatus="rules.role_id ? 'error' : null"
                                class="required"
                            >
                                <span style="display: flex">
                                    <a-select
                                        v-model:value="newFormData.role_id"
                                        :placeholder="
                                            $t('common.select_default_text', [
                                                $t('staff_member.role'),
                                            ])
                                        "
                                        optionFilterProp="label"
                                        show-search
                                    >
                                        <a-select-option
                                            v-for="role in roles"
                                            :key="role.xid"
                                            :value="role.xid"
                                        >
                                            {{ role.display_name }}
                                        </a-select-option>
                                    </a-select>
                                    <RoleAddButton @onAddSuccess="roleAdded" />
                                </span>
                            </a-form-item>
                        </a-col>
                    </a-row>
                    <a-row
                        v-if="newFormData.allow_login && (permsArray.includes('assign_role') || permsArray.includes('admin'))"
                        :gutter="16"
                    >
                        <a-col :xs="24" :sm="24" :md="24" :lg="24">
                            <a-form-item
                                :label="$t('staff_member.password')"
                                name="password"
                                :help="rules.password ? rules.password.message : null"
                                :validateStatus="rules.password ? 'error' : null"
                                class="required"
                            >
                                <a-input-group compact style="display: flex">
                                    <a-input-password
                                        v-model:value="newFormData.password"
                                        :placeholder="
                                            $t('common.placeholder_default_text', [
                                                $t('staff_member.password'),
                                            ])
                                        "
                                        style="flex: 1"
                                    />
                                    <a-tooltip
                                        :title="$t('staff_member.generate_password')"
                                    >
                                        <a-button
                                            type="primary"
                                            @click="generatePassword"
                                        >
                                            <template #icon>
                                                <SyncOutlined />
                                            </template>
                                        </a-button>
                                    </a-tooltip>
                                </a-input-group>
                            </a-form-item>
                        </a-col>
                    </a-row>
                    <a-row :gutter="16">
                        <a-col :xs="24" :sm="24" :md="12" :lg="12">
                            <a-form-item
                                name="status"
                                :help="rules.status ? rules.status.message : null"
                                :validateStatus="rules.status ? 'error' : null"
                            >
                                <template #label>
                                    <span class="required-label">
                                        {{ $t("staff_member.status") }}
                                    </span>
                                </template>
                                <a-radio-group
                                    v-model:value="newFormData.status"
                                    button-style="solid"
                                    size="small"
                                >
                                    <a-radio-button value="active">
                                        {{ $t("common.active") }}
                                    </a-radio-button>
                                    <a-radio-button value="inactive">
                                        {{ $t("common.inactive") }}
                                    </a-radio-button>
                                </a-radio-group>
                            </a-form-item>
                        </a-col>
                    </a-row>
                </a-col>
            </a-row>

            <a-row :gutter="16">
                <a-col :xs="24" :sm="24" :md="24" :lg="24">
                    <a-form-item
                        :label="$t('staff_member.address')"
                        name="address"
                        :help="rules.address ? rules.address.message : null"
                        :validateStatus="rules.address ? 'error' : null"
                    >
                        <a-textarea
                            v-model:value="newFormData.address"
                            :placeholder="
                                $t('common.placeholder_default_text', [
                                    $t('staff_member.address'),
                                ])
                            "
                            :auto-size="{ minRows: 2, maxRows: 3 }"
                        />
                    </a-form-item>
                </a-col>
            </a-row>
        </a-form>
        <template #footer>
            <a-button
                type="primary"
                @click="onSubmit"
                style="margin-right: 8px"
                :loading="loading"
            >
                <template #icon> <SaveOutlined /> </template>
                {{ addEditType == "add" ? $t("common.create") : $t("common.update") }}
            </a-button>
            <a-button @click="onClose">
                {{ $t("common.cancel") }}
            </a-button>
        </template>
    </a-drawer>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import { SaveOutlined, SyncOutlined } from "@ant-design/icons-vue";

const common = window.__composables.common;
const apiAdmin = window.__composables.apiAdmin;
const { useAuthStore } = window.__stores;
const axiosAdmin = window.axiosAdmin;

const props = defineProps({
    formData: Object,
    data: Object,
    visible: Boolean,
    url: String,
    addEditType: String,
    pageTitle: String,
    successMessage: String,
});

const emit = defineEmits(["addEditSuccess", "closed"]);

const { user, permsArray } = common();
const { addEditFileRequestAdmin, loading, rules } = apiAdmin();
const authStore = useAuthStore();

const newFormData = ref({});
const roles = ref([]);
const roleUrl = "roles?limit=10000";

onMounted(() => {
    const rolesPromise = axiosAdmin.get(roleUrl);

    Promise.all([rolesPromise]).then(([rolesResponse]) => {
        roles.value = rolesResponse.data;
    });
});

const onSubmit = () => {
    addEditFileRequestAdmin({
        url: props.url,
        data: newFormData.value,
        successMessage: props.successMessage,
        success: (res) => {
            emit("addEditSuccess", res.xid);

            if (user.value.xid == res.xid) {
                authStore.dispatch("auth/updateUser");
            }
        },
    });
};

const onClose = () => {
    rules.value = {};
    emit("closed");
};

const roleAdded = (xid) => {
    axiosAdmin.get(roleUrl).then((response) => {
        roles.value = response.data;
        // Auto-select the newly created role
        if (xid) {
            newFormData.value.role_id = xid;
        }
    });
};

const generatePassword = () => {
    const length = 12;
    const charset =
        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*";
    let password = "";
    for (let i = 0; i < length; i++) {
        password += charset.charAt(Math.floor(Math.random() * charset.length));
    }
    newFormData.value.password = password;
};

watch(
    () => props.visible,
    (newVal) => {
        if (newVal) {
            newFormData.value = {
                ...props.formData,
                status: props.formData.status || "active",
                allow_login:
                    props.formData.allow_login !== undefined
                        ? props.formData.allow_login
                            ? 1
                            : 0
                        : 1,
            };
        }
    }
);

const drawerWidth = window.innerWidth <= 991 ? "90%" : "45%";
</script>
