<template>
    <theme-table :noneActions="true">
        <span slot="main-title">
            <div class="mb-3">
                {{ $t("User") }}
            </div>
        </span>

        <div slot="body">
            <div class="row">
                <div class="col-sm-6 mb-3">
                    <label class="form-label"
                        >{{ $t("Name") }}<sup class="text-danger">*</sup></label
                    >
                    <input
                        type="text"
                        class="form-control"
                        v-model="form.name" 
                        :placeholder="$t('Name')"
                        :class="{ 'is-invalid': form.errors.has('name') }"
                    />
                    <div
                        class="valid text-danger"
                        v-if="form.errors.has('name')"
                        v-html="form.errors.get('name')"
                    ></div>
                </div>
                <div class="col-sm-6 mb-3">
                    <label class="form-label">{{ $t("Nickname") }}</label>
                    <input
                        type="text"
                        class="form-control"
                        v-model="form.nickname"
                        :placeholder="$t('Nickname')"
                        :class="{ 'is-invalid': form.errors.has('nickname') }"
                    />
                    <div
                        class="valid text-danger"
                        v-if="form.errors.has('nickname')"
                        v-html="form.errors.get('nickname')"
                    ></div>
                </div>
                <div class="col-sm-6 mb-3">
                    <label class="form-label"
                        >{{ $t("Gender")
                        }}<sup class="text-danger">*</sup></label
                    >
                    <Multiselect
                        v-model="form.gender"
                        :placeholder="$t('Gender')"
                        trackBy="gender"
                        value="id"
                        label="gender"
                        :class="{ 'is-invalid': form.errors.has('gender') }"
                        :searchable="true"
                        :options="[
                            { value: 1, gender: $t('Male') },
                            { value: 2, gender: $t('Female') },
                        ]"
                    />
                    <div
                        class="valid text-danger"
                        v-if="form.errors.has('gender')"
                        v-html="form.errors.get('gender')"
                    ></div>
                </div>

                <div class="col-sm-6 mb-3">
                    <label class="form-label">{{ $t("Date of Birth") }}</label>
                    <date-picker
                        v-model="form.dob"
                        type="date"
                        :placeholder="$t('Date of Birth')"
                        valueType="format"
                        format="YYYY-MM-DD"
                        :input-class="
                            form.errors.has('dob')
                                ? 'form-control is-invalid'
                                : 'form-control'
                        "
                    >
                    </date-picker>
                </div>
                <div class="col-sm-6 mb-3">
                    <label class="form-label">
                        {{ $t("Type") }}<sup class="text-danger">*</sup>
                    </label>
                    <Multiselect
                        v-model="form.type"
                        :placeholder="$t('Type')"
                        trackBy="type"
                        value="value"
                        label="type"
                        :class="{ 'is-invalid': form.errors.has('type') }"
                        :searchable="true"
                        :options="[
                            { value: 1, type: $t('User') },
                            { value: 2, type: $t('Co') },
                            { value: 3, type: $t('Employee') },
                        ]"
                    />
                     <div
                        class="valid text-danger"
                        v-if="form.errors.has('type')"
                        v-html="form.errors.get('type')"
                    ></div>
                    <!-- <div
                        class="valid text-danger"
                        v-if="form.errors.has('user_details')"
                        v-html="form.errors.get('user_details')"
                    ></div> -->
                </div>
                <!-- <div class="col-sm-6 mb-3">
                    <label class="form-label">{{ $t('Type') }}<sup class="text-danger">*</sup></label>
                    <Multiselect
                        v-model="form.type"
                        :placeholder="$t('Type')"
                        trackBy="type"
                        value="id"
                        label="type"
                        :class="{ 'is-invalid': form.errors.has('type') }"
                        :searchable="true"
                        :options="[{ value: 1, type: $t('User') }, { value: 2, type:$t('Co') }, { value: 3, type:$t('Employee') }]"
                    />
                    <div class="valid text-danger" v-if="form.errors.has('type')" v-html="form.errors.get('type')"></div>
                </div> -->
                <div class="col-sm-6 mb-3">
                    <label class="form-label">{{ $t("Contact Number") }}</label>
                    <input
                        type="text"
                        class="form-control"
                        v-model="form.contact_number"
                        :placeholder="$t('Contact Number')"
                        :class="{
                            'is-invalid': form.errors.has('contact_number'),
                        }"
                    />
                    <div
                        class="valid text-danger"
                        v-if="form.errors.has('contact_number')"
                        v-html="form.errors.get('contact_number')"
                    ></div>
                </div>
                <div class="col-sm-6 mb-3">
                    <label class="form-label"
                        >{{ $t("Role") }}<sup class="text-danger">*</sup></label
                    >
                    <Multiselect
                        v-model="form.role_id"
                        :disabled="form.id == 1"
                        :placeholder="$t('Role')"
                        trackBy="name"
                        value="id"
                        label="name"
                        :class="{ 'is-invalid': form.errors.has('role_id') }"
                        :searchable="true"
                        :options="rolse"
                    />
                    <div
                        class="valid text-danger"
                        v-if="form.errors.has('role_id')"
                        v-html="form.errors.get('role_id')"
                    ></div>
                </div>
                <div class="col-sm-6 mb-3">
                    <label class="form-label"
                        >{{ $t("User Or Email")
                        }}<sup class="text-danger">*</sup></label
                    >
                    <input
                        type="text"
                        class="form-control"
                        v-model="form.email"
                        :placeholder="$t('User Or Email')"
                        :class="{ 'is-invalid': form.errors.has('email') }"
                    />
                    <div
                        class="valid text-danger"
                        v-if="form.errors.has('email')"
                        v-html="form.errors.get('email')"
                    ></div>
                </div>
                <div class="col-sm-6 mb-3">
                    <label class="form-label"
                        >{{ $t("Password")
                        }}<sup class="text-danger">*</sup></label
                    >
                    <input
                        type="password"
                        class="form-control"
                        v-model="form.password"
                        :placeholder="$t('Password')"
                        :class="{ 'is-invalid': form.errors.has('password') }"
                    />
                    <div
                        class="valid text-danger"
                        v-if="form.errors.has('password')"
                        v-html="form.errors.get('password')"
                    ></div>
                </div>
                <div class="col-sm-6 mb-3">
                    <label class="form-label"
                        >{{ $t("Confirm Password")
                        }}<sup class="text-danger">*</sup></label
                    >
                    <input
                        type="password"
                        class="form-control"
                        v-model="form.confirm_password"
                        :placeholder="$t('Confirm Password')"
                        :class="{
                            'is-invalid': form.errors.has('confirm_password'),
                        }"
                    />
                    <div
                        class="valid text-danger"
                        v-if="form.errors.has('confirm_password')"
                        v-html="form.errors.get('confirm_password')"
                    ></div>
                </div>

                <!-- <div class="col-sm-6 form-group" v-if="form.type">
                    <span class="text_moul">{{ $t("Branch")}}<sup class="text-danger">*</sup></span>
                    <div v-for="branch in form.user_details" :key="branch.id" class="mt-2 border p-2 rounded">
                        <div class="d-flex align-items-center">
                            <input
                                type="checkbox"
                                class="form-check-input me-2"
                                :id="'branchCheck' + branch.id"
                                v-model="branch.selected"
                                :disabled="form.type === 2 && !branch.selected && form.user_details.some((b) => b.selected)"
                                @change="onBranchSelect(branch)"
                            />
                            <label
                                class="form-check-label mb-1"
                                :for="'branchCheck' + branch.id"
                            >
                                {{ branch.name_km }}
                            </label>
                        </div>
                        <div v-if="branch.selected && form.type === 1" class="ms-4 mt-1">
                            <input type="checkbox" class="form-check-input me-2"
                                :id="'repCheck' + branch.id"
                                v-model="branch.is_representative"
                                :disabled="!branch.is_representative && isAnyRepresentativeSelected"
                                @change="onRepresentativeSelect(branch)"
                            />
                            <label class="form-check-label" :for="'repCheck' + branch.id">
                                {{ $t("Representative") }}
                            </label>
                        </div>
                    </div>
                </div> -->
                <!-- <div class="col-sm-6 form-group">
                    <span class="text_moul">{{$t('Branch')}}<sup class="text-danger">*</sup></span>
                    <div v-for="branch in form.user_details" :key="branch.id" class="mt-2">
                        <input class="form-check-input" :id="'invalidCheck' + branch.id" type="checkbox" v-model="branch.selected" />
                        <label class="form-check-label mb-1" :for="'invalidCheck' + branch.id">{{branch.name_km}}</label>
                    </div>
                </div> -->
                <div class="col-sm-6 mb-3">
                    <label class="form-label">{{ $t("Address") }}</label>
                    <suggestions
                        v-model="form.address"
                        :onInputChange="onCountryInputChange"
                    ></suggestions>
                </div>
            </div>
            <div class="d-flex justify-content-end">
                <!-- <button type="button" class="btn btn-dark me-2"><i class="fa-solid fa-arrow-left"></i> {{ $t('Close') }}</button> -->
                <button
                    type="submit"
                    :disabled="form.busy"
                    class="btn btn-success"
                    @click="submitData"
                >
                    <i class="fa-solid fa-floppy-disk"></i>
                    {{ $t("Submit") }}
                </button>
            </div>
        </div>
    </theme-table>
</template>

<script>
import ThemeTable from "../../../components/ThemeTable.vue";
export default {
    components: {
        ThemeTable,
    },
    props: ["id"],
    data() {
        return {
            rolse: [],
            form: new Form({
                id: "",
                code: "",
                name: "",
                nickname: "",
                gender: "",
                dob: "",
                pos_id: "",
                email: "",
                contact_number: "",
                password: "",
                confirm_password: "",
                role_id: "",
                address: "",
                branch_id: "",
                type: "",
                is_representative: false,
                representative_brand: "",
                user_details: [],
            }),
        };
    },
    mounted() {
        this.funGetcomRole();
        this.funshowForm();
    },
    computed: {
        // Returns true if any branch is already representative
        isAnyRepresentativeSelected() {
            return this.form.user_details.some(
                (branch) => branch.is_representative
            );
        },
    },
    methods: {
        funshowForm() {
            axios
                .get("system/users/create", {
                    params: { id: this.id },
                })
                .then((res) => {
                    if (res.data.status == 1) {
                        this.form.fill(res.data.data);
                    } else {
                        this.form.user_details = res.data.user_details;
                    }
                });
        },
        funGetcomRole() {
            axios.get("system/roles").then((res) => {
                this.rolse = res.data;
            });
        },
        async onCountryInputChange(query) {
            if (query.trim().length === 0) {
                return null;
            }
            let data = await axios.get("admin-api/address-autocomplete", {
                params: { searchText: query },
            });
            return data.data;
        },
        submitData() {
            this.form.post("system/users").then((res) => {
                if (res.data.status == 1) {
                    this.form.reset();
                    this.$toast.success(res.data.message);
                    this.$router.push({ name: "User" });
                    this.funGetDataUser();
                } else {
                    this.$toast.warning(res.data.message);
                }
            });
        },
        // submitData() {
        //     this.form.post("system/users").then((res) => {
        //         if (res.data.status == 1) {
        //             this.form.reset();
        //             this.$toast.success(res.data.message);
        //             this.$router.push({ name: "User" });
        //             this.funGetDataUser();
        //         } else {
        //             this.$toast.warning(res.data.message);
        //         }
        //     });
        // },
        onBranchSelect(selectedBranch) {
            // Clear representative if branch is deselected
            if (!selectedBranch.selected) {
                selectedBranch.is_representative = false;
            }

            // For type 2 (Co), only allow one branch to be selected
            if (this.form.type === 2) {
                this.form.user_details.forEach((branch) => {
                    if (branch.id !== selectedBranch.id) {
                        branch.selected = false;
                    }
                });
            }
        },
        onRepresentativeSelect(selectedBranch) {
            // Uncheck all other branches
            this.form.user_details.forEach((branch) => {
                if (branch.id !== selectedBranch.id) {
                    branch.is_representative = false;
                }
            });

            // Set form-level representative fields
            if (selectedBranch.is_representative) {
                this.form.is_representative = true;
                this.form.representative_brand = selectedBranch.id;
            } else {
                this.form.is_representative = false;
                this.form.representative_brand = "";
            }
        },
    },
};
</script>
