import { Button, Form, Input, Spin, Switch, message } from "antd";
import { useContext, useEffect } from "react";
import { useStaff } from "@nice/client";
import DepartmentSelect from "@web/src/components/models/department/department-select";
import { api } from "@nice/client";

import { useAuth } from "@web/src/providers/auth-provider";
import AvatarUploader from "@web/src/components/common/uploader/AvatarUploader";
import { StaffDto } from "@nice/common";
import { UserEditorContext } from "./usermenu";
import toast from "react-hot-toast";
export default function StaffForm() {
	const { user } = useAuth();
	const { create, update } = useStaff(); // Ensure you have these methods in your hooks
	const {
		formLoading,
		modalOpen,
		setModalOpen,
		domainId,
		setDomainId,
		form,
		setFormLoading,
	} = useContext(UserEditorContext);
	const {
		data,
		isLoading,
	}: {
		data: StaffDto;
		isLoading: boolean;
	} = api.staff.findFirst.useQuery(
		{ where: { id: user?.id } },
		{ enabled: !!user?.id }
	);
	const { isRoot } = useAuth();
	async function handleFinish(values: any) {
		const {
			username,
			showname,
			deptId,
			domainId,
			password,
			phoneNumber,
			officerId,
			avatar,
			enabled,
		} = values;
		setFormLoading(true);
		try {
			if (data && user?.id) {
				await update.mutateAsync({
					where: { id: data.id },
					data: {
						username,
						deptId,
						avatar,
						officerId,
						showname,
						domainId,
						password,
						phoneNumber,
						enabled,
					},
				});
			}
			toast.success("提交成功");
			setModalOpen(false);
		} catch (err: any) {
			toast.error(err.message);
		} finally {
			setFormLoading(false);
		}
	}
	useEffect(() => {
		form.resetFields();
		console.log(data?.avatar);
		if (data) {
			form.setFieldValue("username", data.username);
			form.setFieldValue("showname", data.showname);
			form.setFieldValue("domainId", data.domainId);
			form.setFieldValue("deptId", data.deptId);
			form.setFieldValue("avatar", data.avatar);
			form.setFieldValue("phoneNumber", data.phoneNumber);
			form.setFieldValue("officerId", data.officerId);
			form.setFieldValue("enabled", data.enabled);
		}
	}, [data]);
	// useEffect(() => {
	// 	if (!data && domainId) {
	// 		form.setFieldValue("domainId", domainId);
	// 		form.setFieldValue("deptId", domainId);
	// 	}
	// }, [domainId, data as any]);
	return (
		<div className="relative">
			{isLoading && (
				<div className="absolute h-full inset-0 flex items-center justify-center bg-white bg-opacity-50 z-10">
					<Spin />
				</div>
			)}
			<Form
				disabled={isLoading}
				form={form}
				layout="vertical"
				requiredMark="optional"
				autoComplete="off"
				onFinish={handleFinish}>
				<div className=" flex items-center gap-4 mb-2">
					<div>
						<Form.Item name={"avatar"} label="头像" noStyle>
							<AvatarUploader
								placeholder="点击上传头像"
								className="rounded-lg"
								style={{
									width: "120px",
									height: "150px",
								}}></AvatarUploader>
						</Form.Item>
					</div>

					<div className="grid  grid-cols-1  gap-2  flex-1">
						<Form.Item
							noStyle
							rules={[{ required: true }]}
							name={"username"}
							label="帐号">
							<Input
								placeholder="请输入用户名"
								allowClear
								autoComplete="new-username" // 使用非标准的自动完成值
								spellCheck={false}
							/>
						</Form.Item>
						<Form.Item
							noStyle
							rules={[{ required: true }]}
							name={"showname"}
							label="姓名">
							<Input
								placeholder="请输入姓名"
								allowClear
								autoComplete="new-name" // 使用非标准的自动完成值
								spellCheck={false}
							/>
						</Form.Item>
						<Form.Item
							name={"domainId"}
							label="所属域"
							noStyle
							rules={[{ required: true }]}>
							<DepartmentSelect
								placeholder="选择域"
								onChange={(value) => {
									setDomainId(value as string);
								}}
								domain={true}
							/>
						</Form.Item>
						<Form.Item
							noStyle
							name={"deptId"}
							label="所属单位"
							rules={[{ required: true }]}>
							<DepartmentSelect rootId={domainId} />
						</Form.Item>
					</div>
				</div>
				<div className="grid  grid-cols-1  gap-2  flex-1">
					<Form.Item
						// rules={[
						// 	{
						// 		required: false,
						// 		pattern: /^\d{5,18}$/,
						// 		message: "请输入正确的证件号（数字）",
						// 	},
						// ]}
						noStyle
						name={"officerId"}>
						<Input
							placeholder="请输入证件号（可选）"
							autoComplete="off"
							spellCheck={false}
							allowClear
						/>
					</Form.Item>
					<Form.Item
						rules={[
							{
								required: false,
								pattern: /^\d{6,11}$/,
								message: "请输入正确的手机号（数字）",
							},
						]}
						noStyle
						name={"phoneNumber"}
						label="手机号">
						<Input
							placeholder="请输入手机号（可选）"
							autoComplete="new-phone" // 使用非标准的自动完成值
							spellCheck={false}
							allowClear
						/>
					</Form.Item>

					<Form.Item noStyle label="密码" name={"password"}>
						<Input.Password
							placeholder="修改密码"
							spellCheck={false}
							visibilityToggle
							autoComplete="new-password"
						/>
					</Form.Item>
				</div>
			</Form>
		</div>
	);
}
