import { Form, Input, Button, Checkbox, Select, Tabs } from "antd";
import { useLetterEditor } from "../context/LetterEditorContext";
import { SendOutlined } from "@ant-design/icons";
import QuillEditor from "@web/src/components/common/editor/quill/QuillEditor";
import { TusUploader } from "@web/src/components/common/uploader/TusUploader";
import StaffSelect from "../../../staff/staff-select";
import TermSelect from "../../../term/term-select";
import TabPane from "antd/es/tabs/TabPane";
import toast from "react-hot-toast";

export function LetterBasicForm() {
	const { onSubmit, receiverId, termId, form } = useLetterEditor();
	const handleFinish = async (values: any) => {
		await onSubmit(values);
	};
	const handleSubmit = async () => {
		try {
			await form.validateFields();
			form.submit();
			// toast.success("提交成功!");
		} catch (error) {
			// 提取所有错误信息
			const errorMessages = (error as any).errorFields
				.map((field) => field.errors[0])
				.filter(Boolean);

			// 显示 toast 错误提示
			toast.error(
				<div className="flex flex-col gap-1">
					<b>表单校验失败：</b>
					{errorMessages.map((msg, i) => (
						<span key={i}>· {msg}</span>
					))}
				</div>,
				{
					duration: 5000, // 显示 5 秒
					position: "top-center",
				}
			);
		}
	};
	return (
		<div className=" p-6 ">
			<Form
				size="large"
				form={form}
				onFinish={handleFinish}
				initialValues={{
					meta: { tags: [] },
					receivers: [receiverId],
					terms: [termId],
					isPublic: true,
				}}>
				<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
					<Form.Item label="收件人" name={"receivers"}>
						<StaffSelect multiple placeholder="选择收信人员" />
					</Form.Item>
					<Form.Item label="分类" name={"terms"}>
						<TermSelect placeholder="选择信件分类" />
					</Form.Item>
				</div>
				<Form.Item
					name="title"
					rules={[{ required: true, message: "请输入信件标题" }]}>
					<Input
						maxLength={20}
						showCount
						placeholder="请输入信件标题"
					/>
				</Form.Item>
				{/* Tags Input */}
				<Form.Item name={["meta", "tags"]} className="mb-6">
					<Select
						mode="tags"
						showSearch={false}
						suffixIcon={null}
						placeholder="输入标签后按回车添加"
						value={form.getFieldValue(["meta", "tags"]) || []}
						onChange={(value) =>
							form.setFieldValue(["meta", "tags"], value)
						}
						tokenSeparators={[",", " "]}
						className="w-full"
						dropdownStyle={{ display: "none" }}
					/>
				</Form.Item>

				<Tabs defaultActiveKey="1">
					{/* Content Editor */}
					<TabPane tab="正文" key="1">
						<Form.Item
							name="content"
							rules={[
								{ required: true, message: "请输入正文内容" },
							]}
							required={false}>
							<div className="rounded-xl border  border-white hover:ring-1 ring-white transition-all duration-300 ease-in-out bg-slate-100">
								<QuillEditor
									maxLength={10000}
									placeholder="请输入内容"
									minRows={6}
									onChange={(content) =>
										form.setFieldValue("content", content)
									}
								/>
							</div>
						</Form.Item>
					</TabPane>
					<TabPane tab="附件" key="2">
						<div className="rounded-xl border  border-white hover:ring-1 ring-white transition-all duration-300 ease-in-out bg-slate-100">
							<Form.Item name="resources" required={false}>
								<TusUploader
									onChange={async (resources) => {
										// console.log(resources);
										form.setFieldValue(
											"resources",
											resources
										);
										// console.log(
										// 	form.getFieldValue("resources")
										// );
									}}
								/>
							</Form.Item>
						</div>
					</TabPane>
				</Tabs>
				{/* <Button
					onClick={() => {
						console.log(form.getFieldValue("resources"));
					}}></Button> */}
				{/* Footer Actions */}
				<div className="flex flex-col-reverse sm:flex-row items-center justify-between gap-4 mt-2  ">
					<Form.Item name="isPublic" valuePropName="checked">
						<Checkbox className="text-gray-600 hover:text-gray-900 transition-colors text-sm">
							是否公开
						</Checkbox>
					</Form.Item>
					<div className="flex gap-2 ">
						<Form.Item name={["meta", "signature"]}>
							<Input
								maxLength={15}
								style={{
									width: 150,
								}}
								// showCount
								placeholder="签名"
							/>
						</Form.Item>
						<Button
							type="primary"
							onClick={handleSubmit}
							size="large"
							icon={<SendOutlined />}
							className="w-full sm:w-40">
							发送信件
						</Button>
					</div>
				</div>
			</Form>
		</div>
	);
}
