import { _objectSpread2 } from "../../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { _asyncToGenerator } from "../../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
import { isWalkIn } from "../../../utils.js";
import { uniqueByField } from "../../utils.js";
import Drawer$1 from "../../../components/drawer/index.js";
import { getWaiverTitle } from "../utils.js";
import { formatAddFormValues, sortFormValues } from "../../../forms/format.js";
import React, { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
import { Avatar, Button, Checkbox, Empty, Input, Spin } from "antd";
import { image, locales } from "@pisell/utils";
import PlusCircle from "@pisell/icon/es/PlusCircle";
import User01 from "@pisell/icon/es/User01";
import SearchLg from "@pisell/icon/es/SearchLg";
import classNames from "classnames";
import Plus from "@pisell/icon/es/Plus";
import "./SelectDrawer.less";
//#region src/components/booking/info/clientVariant/vertical/SelectDrawer.tsx
const ActionItem = (props) => {
	return /* @__PURE__ */ React.createElement("div", {
		className: "vertical-client-select-drawer-item-wrap",
		onClick: props.onClick
	}, /* @__PURE__ */ React.createElement("span", { className: "vertical-client-item-icon-wrap" }, /* @__PURE__ */ React.createElement(Plus, { style: {
		fontSize: 28,
		color: "#7F56D9"
	} })), /* @__PURE__ */ React.createElement("span", { className: "vertical-client-item-title" }, props.title));
};
const Item = ({ cover, onClick, title, desc, coverSize, checked, style, loading, waiverForm }) => {
	const waiverTitle = useMemo(() => {
		return getWaiverTitle(waiverForm);
	}, [waiverForm]);
	return /* @__PURE__ */ React.createElement("div", {
		className: classNames("vertical-client-select-drawer-item-wrap", { ["checked"]: checked }),
		onClick,
		style
	}, /* @__PURE__ */ React.createElement(Avatar, {
		className: "pisell-lowcode__booking-client-list-item-avatar",
		src: image.ali(cover, 100) || void 0,
		size: coverSize || 56,
		icon: /* @__PURE__ */ React.createElement(User01, { className: "pisell-lowcode__booking-client-list-item-avatar-icon" })
	}), /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__booking-client-list-item-info" }, /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__booking-client-list-item-info-name" }, title), /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__booking-client-list-item-info-desc" }, (desc || []).map((d) => /* @__PURE__ */ React.createElement("div", {
		className: "",
		title: d
	}, d))), /* @__PURE__ */ React.createElement("div", {
		className: "pisell-lowcode__booking-client-list-item-info-desc-waiver",
		title: waiverTitle
	}, (waiverForm || []).map((item) => {
		return /* @__PURE__ */ React.createElement("span", null, item.form_title, ":", item.is_filled ? /* @__PURE__ */ React.createElement("span", { className: "pisell-lowcode__booking-client-list-item-info-desc-filled" }, locales.getText("pisell2.text.filled")) : /* @__PURE__ */ React.createElement("span", { className: "pisell-lowcode__booking-client-list-item-info-desc-not-filled" }, locales.getText("pisell2.text.not-filled")), "; ");
	}))), /* @__PURE__ */ React.createElement(Spin, { spinning: !!loading }));
};
const defaultArr = [];
const SelectDrawer = (props, ref) => {
	const { autoFocus, onClose, handleSelectClient, handleCreateItem, childrenValue, handleSelectPet, formData, searchChange, options, loading, holder, client, loadMore, showPet, handleAddPet, modalOpen, franchiseeLoading, showHeader, showWalkIn } = props;
	const form = (formData === null || formData === void 0 ? void 0 : formData[0]) || {};
	const valList = (childrenValue === null || childrenValue === void 0 ? void 0 : childrenValue[form.id]) || defaultArr;
	const [_value, setValue] = useState(valList);
	const clientRef = useRef();
	const searchRef = useRef();
	const [open, setOpen] = useState(false);
	const [search, setSearch] = useState("");
	useEffect(() => {
		setValue(valList.map((item) => _objectSpread2(_objectSpread2({}, item), {}, { id: item.id || item.form_record_id })));
	}, [valList, open]);
	useEffect(() => {
		if (!modalOpen) setOpen(false);
	}, [modalOpen]);
	const closeDrawer = () => {
		setOpen(false);
		setSearch("");
		onClose === null || onClose === void 0 || onClose();
	};
	const handleOpenModal = () => {
		setOpen(true);
		if (autoFocus) setTimeout(() => {
			var _searchRef$current, _searchRef$current$fo;
			(_searchRef$current = searchRef.current) === null || _searchRef$current === void 0 || (_searchRef$current$fo = _searchRef$current.focus) === null || _searchRef$current$fo === void 0 || _searchRef$current$fo.call(_searchRef$current);
		}, 400);
	};
	useImperativeHandle(ref, () => {
		return {
			open: handleOpenModal,
			close: () => {
				setOpen(false);
			},
			setSearch: (val) => {
				setSearch(val);
			}
		};
	});
	useEffect(() => {
		if (!open) clientRef.current = null;
	}, [open]);
	const getNickname = useCallback((item) => {
		if (isWalkIn(item === null || item === void 0 ? void 0 : item.id)) return locales.getText("pisell2.text.select-a-customer");
		const firstLastName = item.first_name || item.last_name ? `${item.first_name} ${item.last_name}` : "";
		return item.name || (item.display_name || "").trim() || (item.nickname || "").trim() || firstLastName.trim() || "";
	}, [locales.localeMap]);
	const handleAddClient = () => {
		handleCreateItem(() => {
			setSearch("");
		});
	};
	const handleChildrenValueChange = function() {
		var _ref = _asyncToGenerator(function* (value, item) {
			let clientId = client.id;
			if (!(client === null || client === void 0 ? void 0 : client.id) || client.id === 1) {
				var _clientRef$current;
				clientId = ((_clientRef$current = clientRef.current) === null || _clientRef$current === void 0 ? void 0 : _clientRef$current.id) || item.id;
			}
			if (mode === "single") {
				if (!(client === null || client === void 0 ? void 0 : client.id) || client.id === 1) yield handleSelectClient([item]);
				handleSelectPet({ [form.id]: formatAddFormValues({
					clientId,
					value: [value],
					data_range: holder.data_range
				}) });
				setTimeout(() => {
					closeDrawer();
				});
			} else {
				const index = _value.findIndex((item) => item.id === value.id || item.form_record_id === value.id);
				if (!clientRef.current) clientRef.current = item;
				if (index >= 0) {
					const newList = [..._value];
					newList.splice(index, 1);
					setValue(formatAddFormValues({
						clientId,
						value: newList,
						data_range: holder.data_range
					}));
				} else setValue(formatAddFormValues({
					clientId,
					value: [..._value, value],
					data_range: holder.data_range
				}));
			}
		});
		return function handleChildrenValueChange(_x, _x2) {
			return _ref.apply(this, arguments);
		};
	}();
	const mode = useMemo(() => {
		if (["form"].includes(holder === null || holder === void 0 ? void 0 : holder.type)) return "single";
		if (["table"].includes(holder === null || holder === void 0 ? void 0 : holder.type)) return "multiple";
		return holder === null || holder === void 0 ? void 0 : holder.type;
	}, [holder === null || holder === void 0 ? void 0 : holder.type]);
	const handleOk = function() {
		var _ref2 = _asyncToGenerator(function* () {
			var _holder$form;
			if (!(client === null || client === void 0 ? void 0 : client.id) || (client === null || client === void 0 ? void 0 : client.id) === 1) yield handleSelectClient([clientRef.current]);
			handleSelectPet({ [holder === null || holder === void 0 || (_holder$form = holder.form) === null || _holder$form === void 0 ? void 0 : _holder$form.id]: _value });
			closeDrawer();
		});
		return function handleOk() {
			return _ref2.apply(this, arguments);
		};
	}();
	const handleClientClick = function() {
		var _ref3 = _asyncToGenerator(function* (item) {
			yield handleSelectClient([item]);
			if (mode === "multiple") {
				var _item$form_record;
				const isHasChildren = _value.some((val) => item.form_record.some((f) => f.id || f.form_record_id === val.id || val.form_record_id));
				handleSelectPet({ [form.id]: uniqueByField([...sortFormValues(_value, item.id), ...isHasChildren ? [] : formatAddFormValues({
					clientId: item.id,
					data_range: holder.data_range,
					value: (_item$form_record = item.form_record) === null || _item$form_record === void 0 ? void 0 : _item$form_record.map((f) => _objectSpread2(_objectSpread2({}, f), {}, { customer: item }))
				})], "id") });
			}
			closeDrawer();
		});
		return function handleClientClick(_x3) {
			return _ref3.apply(this, arguments);
		};
	}();
	console.log("options7777", options);
	return /* @__PURE__ */ React.createElement(Drawer$1, {
		showGoBack: showHeader,
		title: showHeader && locales.getText("pisell2.text.select-customer"),
		open,
		onClose: closeDrawer,
		header: /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(Input, {
			ref: searchRef,
			prefix: /* @__PURE__ */ React.createElement(SearchLg, null),
			style: {
				margin: "16px 0",
				height: 44
			},
			placeholder: locales.getText("pisell2.booking.text.search-placeholder"),
			value: search,
			allowClear: true,
			onChange: (e) => {
				setSearch(e.target.value);
				if (searchChange) searchChange(e.target.value);
			}
		})),
		width: 300,
		titleNoWrap: true,
		getContainer: false,
		destroyOnClose: true,
		push: { distance: 180 },
		footer: mode === "multiple" && /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(Button, {
			block: true,
			type: "primary",
			onClick: handleOk,
			loading: !!franchiseeLoading
		}, locales.getText("pisell2.text.apply")))
	}, /* @__PURE__ */ React.createElement("div", { className: "vertical-client-select-drawer-content-wrap" }, /* @__PURE__ */ React.createElement("div", { className: "vertical-client-select-drawer-top" }, /* @__PURE__ */ React.createElement(ActionItem, {
		title: locales.getText("pisell2.text.create-new-customer"),
		onClick: handleAddClient
	}), showWalkIn ? /* @__PURE__ */ React.createElement(ActionItem, {
		title: "Walk-In",
		onClick: () => {
			handleSelectClient([]);
			closeDrawer();
		}
	}) : null), /* @__PURE__ */ React.createElement(Spin, {
		spinning: !!loading,
		delay: 500
	}, !!options.length ? options.map((item) => {
		var _holder$form2;
		let displayEmail = item === null || item === void 0 ? void 0 : item.email;
		let displayPhone = item === null || item === void 0 ? void 0 : item.phone;
		if (!displayEmail && !displayPhone) {
			var _item$contacts_info, _item$contacts_info2;
			displayEmail = item === null || item === void 0 || (_item$contacts_info = item.contacts_info) === null || _item$contacts_info === void 0 || (_item$contacts_info = _item$contacts_info.value) === null || _item$contacts_info === void 0 ? void 0 : _item$contacts_info.email;
			displayPhone = item === null || item === void 0 || (_item$contacts_info2 = item.contacts_info) === null || _item$contacts_info2 === void 0 || (_item$contacts_info2 = _item$contacts_info2.value) === null || _item$contacts_info2 === void 0 || (_item$contacts_info2 = _item$contacts_info2.phone) === null || _item$contacts_info2 === void 0 ? void 0 : _item$contacts_info2.phone;
		}
		return /* @__PURE__ */ React.createElement("div", {
			className: "vertical-client-select-drawer-content-item",
			key: item.id
		}, /* @__PURE__ */ React.createElement(Item, {
			onClick: () => handleClientClick(item),
			cover: item.cover,
			title: getNickname(item),
			desc: [displayEmail, displayPhone],
			checked: item.id === client.id,
			style: showPet ? { marginBottom: 6 } : {},
			loading: franchiseeLoading === item.id,
			waiverForm: item.waiver_form
		}), showPet && /* @__PURE__ */ React.createElement("div", { className: "vertical-client-select-drawer-content-item-children" }, ((item === null || item === void 0 ? void 0 : item.form_record) || []).map((f) => {
			const checked = _value.some((item) => item.id === f.id || item.form_record_id === f.id);
			return /* @__PURE__ */ React.createElement("div", {
				onClick: () => {
					handleChildrenValueChange(_objectSpread2(_objectSpread2({}, f), {}, { customer: item }), item);
				},
				id: `${f.id}`,
				key: f.id,
				className: classNames("vertical-client-select-drawer-content-item-children-item", { ["checked"]: checked })
			}, mode === "multiple" && /* @__PURE__ */ React.createElement(Checkbox, { checked }), /* @__PURE__ */ React.createElement(Item, {
				coverSize: 48,
				title: f.main_field,
				loading: false
			}));
		}), /* @__PURE__ */ React.createElement("div", {
			className: "pisell-lowcode__custom-select-create",
			onClick: () => {
				handleAddPet === null || handleAddPet === void 0 || handleAddPet(item);
			},
			style: { padding: 16 }
		}, /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(PlusCircle, { className: "pisell-lowcode__custom-select-create-icon" }), /* @__PURE__ */ React.createElement("span", { className: "pisell-lowcode__custom-select-create-txt" }, `${locales.getText("pisell2.text.create-new")} ${((_holder$form2 = holder.form) === null || _holder$form2 === void 0 ? void 0 : _holder$form2.title) || "-"}`))), /* @__PURE__ */ React.createElement("div", null)));
	}) : /* @__PURE__ */ React.createElement(Empty, { image: Empty.PRESENTED_IMAGE_SIMPLE }), /* @__PURE__ */ React.createElement("div", null, loadMore))));
};
var SelectDrawer_default = forwardRef(SelectDrawer);
//#endregion
export { SelectDrawer_default as default };
