import { createContext, useContext, ReactNode } from "react";
import { Form, FormInstance } from "antd";
import { api, usePost } from "@nice/client";
import toast from "react-hot-toast";
import { useNavigate } from "react-router-dom";
import { PostState, PostType } from "@nice/common";
import dayjs from "dayjs";

export interface LetterFormData {
	title: string;
	content: string;
	resources?: string[];
	receivers?: string[];
	terms?: string[];
	isPublic?: boolean;
	signature?: string;
	meta: {
		tags: string[];
		signature?: string;
	};
}
interface LetterEditorContextType {
	onSubmit: (values: LetterFormData) => Promise<void>;
	receiverId?: string;
	termId?: string;
	form: FormInstance<LetterFormData>;
}

interface LetterFormProviderProps {
	children: ReactNode;
	receiverId?: string;
	termId?: string;
}

const LetterEditorContext = createContext<LetterEditorContextType | null>(null);

export function LetterFormProvider({
	children,
	receiverId,
	termId,
}: LetterFormProviderProps) {
	const { create } = usePost();
	const navigate = useNavigate();
	const [form] = Form.useForm<LetterFormData>();

	const onSubmit = async (data: LetterFormData) => {
		try {
			console.log(data);
			const receivers = data?.receivers;
			const terms = data?.terms;
			delete data.receivers;
			delete data.terms;
			const result = await create.mutateAsync({
				data: {
					...data,
					type: PostType.POST,
					terms: {
						connect: (terms || [])?.filter(Boolean).map((id) => ({
							id,
						})),
					},
					receivers: {
						connect: (receivers || [])
							?.filter(Boolean)
							.map((id) => ({
								id,
							})),
					},
					state: PostState.PENDING,
					isPublic: data?.isPublic,
					resources: data.resources?.length
						? {
							connect: (
								data.resources?.filter(Boolean) || []
							).map((fileId) => ({
								fileId,
							})),
						}
						: undefined,
				},
			});
			const formattedDateTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
			// 创建包含信件编号和提交时间的文本
			const fileContent = `信件编号: ${result.id}\n投递时间: ${formattedDateTime}`;
			// 创建包含信件编号和提交时间的Blob对象
			const blob = new Blob([fileContent], { type: "text/plain" });
			// 创建下载链接
			const downloadUrl = window.URL.createObjectURL(blob);
			const link = document.createElement("a");
			link.href = downloadUrl;
			link.download = `信件编号-${result.id}.txt`; // 设置下载文件名
			document.body.appendChild(link);
			link.click();
			document.body.removeChild(link);
			window.URL.revokeObjectURL(downloadUrl);

			toast.success(
				`信件投递成功！信件编号已保存到本地，请妥善保管用于进度查询`,
				{
					duration: 5000, // 10秒
				}
			);
			// navigate(`/${result.id}/detail`, {
			// 	replace: true,
			// 	state: { scrollToTop: true },
			// });
			form.resetFields();
		} catch (error) {
			console.error("Error submitting form:", error);
			toast.error("操作失败，请重试！");
		}
	};

	return (
		<LetterEditorContext.Provider
			value={{
				onSubmit,
				receiverId,
				termId,
				form,
			}}>
			{children}
		</LetterEditorContext.Provider>
	);
}

export const useLetterEditor = () => {
	const context = useContext(LetterEditorContext);
	if (!context) {
		throw new Error(
			"useLetterEditor must be used within LetterFormProvider"
		);
	}
	return context;
};
