<template>
	<form @submit.prevent="vendor.submit()">
		<v-defaults-provider
			:defaults="{
        global: {
          disabled: vendor.loading,
        },
      }"
		>
			<v-row tag="form" @submit.prevent="submit($v)">
				<v-col class="pa-0 px-3 pa-md-6" cols="12" md="4">First Name</v-col>
				<v-col cols="12" md="8">
					<v-text-field
						v-model="vendor.data.vendor_agents.first_name"
						:error-messages="vendor.error.get('vendor_agents.first_name')"
						label="First Name"
					></v-text-field>
				</v-col>

				<v-col class="pa-0 px-3 pa-md-6" cols="12" md="4">Last Name</v-col>
				<v-col cols="12" md="8">
					<v-text-field
						v-model="vendor.data.vendor_agents.last_name"
						:error-messages="vendor.error.get('vendor_agents.last_name')"
						label="First Name"
					></v-text-field>
				</v-col>

				<v-col class="pa-0 px-3 pa-md-6" cols="12" md="4">E-mail</v-col>
				<v-col cols="12" md="8">
					<v-text-field
						v-model="vendor.data.vendor_agents.login"
						:error-messages="vendor.error.get('vendor_agents.login')"
						disabled
						label="E-mail"
					></v-text-field>
				</v-col>

				<!-- Phone -->
				<v-col class="pa-0 px-3 pa-md-6" cols="12" md="4">Phones</v-col>
				<v-col cols="12" md="8">
					<div
						v-if="vendor.data.vendor_agents.phones.length == 0"
						class="bg-grey-lighten-4 py-10 text-center text-disabled rounded"
					>
						No Phone
					</div>
					<v-expansion-panels v-model="vendor.dataPhonePanel" class="mb-3">
						<template
							v-for="(phone, index) in vendor.data.vendor_agents.phones"
							:key="index"
						>
							<v-expansion-panel>
								<v-expansion-panel-title>
									{{ phone.number ? `+${phone.country} ${phone.number}` : "New" }}
								</v-expansion-panel-title>
								<v-expansion-panel-text>
									<v-row>
										<v-col cols="6">
											<v-select
												v-model="phone.type"
												:hide-details="true"
												:items="vendor.dataPhoneTypes"
												item-title="title"
												item-value="value"
												label="Phone type"
											></v-select>
										</v-col>
										<v-col cols="6">
											<v-autocomplete
												v-model="phone.country"
												:hide-details="true"
												:items="
												  place.country.data.map((item) => ({
													value: item.phone.code.replace('+', ''),
													title: `${item.phone.code} - ${item.name}`,
												  }))
												"
												:loading="place.country.loading"
												item-title="title"
												item-value="value"
												label="Country code"
												@update:model-value="vendor.dataPhoneValidate($event, phone)"
											></v-autocomplete>
										</v-col>
										<v-col cols="12">
											<v-text-field
												v-model="phone.number"
												v-imask="mask.phoneCountry(phone.country)"
												label="Phone"
												@update:model-value="vendor.dataPhoneValidate($event, phone)"
											></v-text-field>
											{{ phone.number }}
										</v-col>
									</v-row>
									<v-card-actions class="mx-n6 mb-n4 border-t">
										<v-spacer></v-spacer>
										<v-btn color="error" @click="vendor.dataPhoneRemove(phone)">
											<v-icon>mdi-delete</v-icon>
											<span class="ms-2">Remove</span>
										</v-btn>
									</v-card-actions>
								</v-expansion-panel-text>
							</v-expansion-panel>
						</template>
					</v-expansion-panels>

					<div class="text-center">
						<v-btn color="primary" @click="vendor.dataPhoneAdd()">
							Add Phone
						</v-btn>
					</div>
				</v-col>

				<!-- Addresses -->
				<v-col class="pa-0 pa-md-6" cols="12" md="4">Addresses</v-col>
				<v-col cols="12" md="8">
					<div
						v-if="vendor.data.vendor_agents.addresses.length == 0"
						class="bg-grey-lighten-4 py-10 text-center text-disabled rounded"
					>
						No Address
					</div>
					<v-expansion-panels v-model="vendor.dataAddressPanel" class="mb-3">
						<template
							v-for="(addr, index) in vendor.data.vendor_agents.addresses"
						>
							<v-expansion-panel>
								<v-expansion-panel-title>
									{{ addr.full_address || "New" }}
								</v-expansion-panel-title>
								<v-expansion-panel-text>
									<v-defaults-provider
										:defaults="{
                      global: {
                        hideDetails: true,
                      },
                    }"
									>
										<v-row cols="12">
											<v-col cols="12">
												<app-place
													label="Search address"
													@change="vendor.dataAddressOnSearch($event, addr)"
												></app-place>
											</v-col>

											<v-col cols="12">
												<v-divider></v-divider>
											</v-col>

											<v-col cols="12" md="12">
												<v-text-field
													v-model="addr.address"
													label="Address"
													@update:model-value="vendor.dataAddressOnChange(addr)"
												></v-text-field>
											</v-col>

											<v-col cols="12" md="6">
												<v-text-field
													v-model="addr.post_code"
													label="Post code"
													@update:model-value="vendor.dataAddressOnChange(addr)"
												></v-text-field>
											</v-col>

											<v-col cols="12" md="6">
												<v-text-field
													v-model="addr.suburb"
													label="Suburb"
													@update:model-value="vendor.dataAddressOnChange(addr)"
												></v-text-field>
											</v-col>

											<v-col cols="12" md="6">
												<v-text-field
													v-model="addr.city"
													label="City"
													@update:model-value="vendor.dataAddressOnChange(addr)"
												></v-text-field>
											</v-col>

											<v-col cols="12" md="6">
												<v-text-field
													v-model="addr.country"
													label="Country"
													@update:model-value="vendor.dataAddressOnChange(addr)"
												></v-text-field>
											</v-col>
										</v-row>
										<br/>
									</v-defaults-provider>

									<v-card-actions class="mx-n6 mb-n4 border-t">
										<v-spacer></v-spacer>
										<v-btn color="error" @click="vendor.dataAddressRemove(addr)">
											<v-icon>mdi-delete</v-icon>
											<span class="ms-2">Remove</span>
										</v-btn>
									</v-card-actions>
								</v-expansion-panel-text>
							</v-expansion-panel>
						</template>
					</v-expansion-panels>

					<div class="text-center">
						<v-btn color="primary" @click="vendor.dataAddressAdd()"
						>Add Address
						</v-btn>
					</div>
				</v-col>

				<v-col class="pa-0 pa-md-6" cols="12" md="4">Password</v-col>
				<v-col cols="12" md="8">
					<v-expansion-panels v-model="expansionPassword">
						<v-expansion-panel value="password">
							<v-expansion-panel-title>Change Password</v-expansion-panel-title>
							<v-expansion-panel-text>
								<v-row>
									<v-col cols="12" md="4">
										<v-text-field
											label="Previous Password"
											v-model.trim="vendor.data.vendor_agents.old_password"
											:error="
                        $v.vendor.data.vendor_agents.old_password.$dirty &&
                        $v.vendor.data.vendor_agents.old_password.$error
                      "
											:error-messages="
                        getErrors($v.vendor.data.vendor_agents.old_password)
                      "
											@blur="$v.vendor.data.vendor_agents.old_password.$touch()"
											@click:append-inner="showOldPassword = !showOldPassword"
											:type="!showOldPassword ? 'password' : 'text'"
											:append-inner-icon="
                        showOldPassword ? 'mdi-eye' : 'mdi-eye-off'
                      "
										/>
									</v-col>
									<v-col cols="12" md="4">
										<v-text-field
											label="New Password"
											v-model.trim="vendor.data.vendor_agents.password"
											:error="
                        $v.vendor.data.vendor_agents.password.$dirty &&
                        $v.vendor.data.vendor_agents.password.$error
                      "
											:error-messages="
                        getErrors($v.vendor.data.vendor_agents.password)
                      "
											@blur="$v.vendor.data.vendor_agents.password.$touch()"
											@click:append-inner="showPassword = !showPassword"
											:type="!showPassword ? 'password' : 'text'"
											:append-inner-icon="
                        showPassword ? 'mdi-eye' : 'mdi-eye-off'
                      "
										/>
									</v-col>
									<v-col cols="12" md="4">
										<v-text-field
											label="Confirm New Password"
											v-model.trim="
                        vendor.data.vendor_agents.password_confirmation
                      "
											:error="
                        $v.vendor.data.vendor_agents.password_confirmation
                          .$dirty &&
                        $v.vendor.data.vendor_agents.password_confirmation.$error
                      "
											:error-messages="
                        getErrors(
                          $v.vendor.data.vendor_agents.password_confirmation,
                        )
                      "
											@blur="
                        $v.vendor.data.vendor_agents.password_confirmation.$touch()
                      "
											@click:append-inner="
                        showPasswordConfirm = !showPasswordConfirm
                      "
											:type="!showPasswordConfirm ? 'password' : 'text'"
											:append-inner-icon="
                        showPasswordConfirm ? 'mdi-eye' : 'mdi-eye-off'
                      "
										/>
									</v-col>
								</v-row>
							</v-expansion-panel-text>
						</v-expansion-panel>
					</v-expansion-panels>
				</v-col>

				<v-alert v-if="errorSubmit.show" closable class="my-3" type="error">
					{{ errorSubmit.message }}
				</v-alert>

				<v-alert v-if="vendor.error.exists()" type="error">
					There is validation errors
				</v-alert>

				<v-alert v-if="vendor.success" type="success"> Vendor updated</v-alert>

				<v-col class="d-flex align-center border-t" cols="12">
					<v-spacer></v-spacer>
					<v-btn :loading="vendor.loading" color="primary" type="submit">
						<span>Save</span>
					</v-btn>
				</v-col>
			</v-row>
		</v-defaults-provider>
	</form>
</template>

<script setup>
const {computed, ref} = Vue;
const {useVuelidate} = Vuelidate;
const {maxLength, minLength, sameAs} = VuelidateValidators;

const AppPlace = Vue.defineAsyncComponent(() =>
	loadModule(`${SAS_URL}/src/components/AppPlace.vue`, options),
);

const place = usePlace();
const mask = useImask();
const showPasswordConfirm = ref(false);
const showPassword = ref(false);
const showOldPassword = ref(false);
const expansionPassword = ref(null);
const errorSubmit = ref({show: false, message: null});

const vendor = useAxios({
	method: "PUT",
	url: `/vendor/agents/${useUserStore().getUser.id}`,
	dataPhonePanel: false,
	dataAddressPanel: false,
	data: {
		vendor_agents: {
			old_password: undefined,
			password: undefined,
			password_confirmation: undefined,
			...useUserStore().getUser,
		},
	},
	dataPhoneTypes: [
		{value: "cellphone", title: "Mobile"},
		{value: "residential", title: "Residential"},
	],
	dataPhoneDefault(phone = {}) {
		return {
			country: "",
			country_code: "",
			number: "",
			type: "cellphone",
			full_number: "",
			national_number: "",
			formatted_international_number: "",
			formatted_national_number: "",
			uri: "",
			...phone,
		};
	},
	dataPhoneAdd(phone = {}) {
		phone = vendor.dataPhoneDefault(phone);
		vendor.data.vendor_agents.phones.push(phone);
		vendor.dataPhonePanel = vendor.data.vendor_agents.phones.length - 1;
	},
	dataPhoneRemove(phone) {
		const index = vendor.data.vendor_agents.phones.indexOf(phone);
		vendor.data.vendor_agents.phones.splice(index, 1);
		vendor.dataPhonePanel = vendor.data.vendor_agents.phones.length - 1;
	},
	dataPhoneValidate(phone, phoneObject) {
		if (!phone.country || !phone.number) return;
		phone.full_number = `+${phone.country}${phone.number}`;
	},
	dataAddressDefault(addr = {}) {
		return {
			address: "",
			suburb: "",
			city: "",
			state: "",
			country: "",
			country_code: "",
			post_code: "",
			latitude: "",
			longitude: "",
			full_address: "",
			type: "residential",
			...addr,
		};
	},
	dataAddressAdd(addr = {}) {
		addr = vendor.dataAddressDefault(addr);
		vendor.data.vendor_agents.addresses.push(addr);
		vendor.dataAddressPanel = vendor.data.vendor_agents.addresses.length - 1;
	},
	dataAddressRemove(addr) {
		const index = vendor.data.vendor_agents.addresses.indexOf(addr);
		vendor.data.vendor_agents.addresses.splice(index, 1);
		vendor.dataAddressPanel = vendor.data.vendor_agents.addresses.length - 1;
	},
	dataAddressOnChange(addr) {
		addr.type = addr.type || "residential";
		addr.full_address = [
			addr.address,
			addr.suburb,
			addr.city && addr.state ? `${addr.city} - ${addr.state}` : null,
			addr.post_code,
			addr.country,
		]
			.filter((v) => !!v)
			.join(", ");
	},
	dataAddressOnSearch(ev, addr) {
		addr.address = [ev.number || null, ev.address || null]
			.filter((v) => !!v)
			.join(", ");

		addr.suburb = ev.suburb;
		addr.city = ev.city;
		addr.state = ev.state_code;
		addr.country = ev.country;
		addr.country_code = ev.country_code;
		addr.post_code = ev.postcode;
		addr.latitude = ev.lat;
		addr.longitude = ev.lng;

		addr.full_address = [
			ev.number || null,
			ev.address || null,
			ev.suburb || null,
			ev.city || null,
			ev.state || null,
			ev.country || null,
		]
			.filter((v) => !!v)
			.join(", ");
	},
	onSuccess() {
		useUserStore().setSyncUser();
	},
	onError(e) {
		errorSubmit.value = {
			show: true,
			message: e.data.message === 'Attempt to read property "id" on bool' ? "An unknown error occurred." : e.data.message ?? "An unknown error occurred."
		};
	},
});
const rules = ref({
	vendor: {
		data: {
			vendor_agents: {
				old_password: {
					custom: (value) => {
						let valid = true;
						if (expansionPassword.value && !value) valid = false;

						return valid;
					},
				},
				password: {
					custom: (value) => {
						let valid = true;
						if (expansionPassword.value && !value) valid = false;

						return valid;
					},
					minLength: minLength(5),
					maxLength: maxLength(30),
				},
				password_confirmation: {
					custom: (value) => {
						let valid = true;
						if (expansionPassword.value && !value) valid = false;

						return valid;
					},
					sameAs: sameAs(computed(() => vendor.data.vendor_agents.password)),
				},
			},
		},
	},
});
const $v = useVuelidate(rules.value, {vendor});

const getErrors = ($v) => {
	if ($v.$dirty && $v.$errors?.length)
		return $v.$errors.map((e) => {
			switch (e.$validator) {
				case "sameAs":
					return "Passwords do not match";
				case "custom":
					return "Value is required";
				default:
					return e.$message;
			}
		});
	else return [];
};

const submit = (v) => {
	$v.value.vendor.data.vendor_agents.$touch();

	if ($v.value.vendor.data.vendor_agents.$invalid) return;

	vendor.submit();
};
</script>
