import { Form, FormInstance, message } from "antd";
import { api } from "@nice/client";
import { createContext, useContext, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { getQueryKey } from "@trpc/react-query";

interface CodeManageContextType {
    editForm: FormInstance<any>;
    isLoading: boolean;
    currentShareCodes: ShareCodeWithResource;
    currentPage: number;
    setCurrentPage: (page: number) => void;
    pageSize: number;
    deletShareCode: (id: string) => void;
    updateCode: (expiresAt: Date, canUseTimes: number) => void
    setCurrentCodeId: (id: string) => void,
    currentCodeId: string | null,
    searchRefetch: () => void,
    setSearchKeyword: (keyword: string) => void,
    currentCode: string | null,
    setCurrentCode: (code: string) => void
}

interface ShareCodeWithResource {
    items: {
        id: string;
        code: string;
        fileName: string;
        fileSize: number;
        expiresAt: string;
        createdAt: string;
        canUseTimes: number;
        resource: {
            id: string;
            type: string;
            url: string;
            meta: any;
        }
    }[],
    totalPages: number
}

export const CodeManageContext = createContext<CodeManageContextType | null>(null);

export const CodeManageProvider = ({ children }: { children: React.ReactNode }) => {
    const [editForm] = Form.useForm();
    const [currentPage, setCurrentPage] = useState(1);
    const [currentCodeId, setCurrentCodeId] = useState<string | null>()
    const [currentCode, setCurrentCode] = useState<string | null>()
    const queryClient = useQueryClient();
    const pageSize = 8;
    // 在组件顶部添加
    const [searchKeyword, setSearchKeyword] = useState('');
    // 构建查询条件
    const whereCondition = {
        deletedAt: null,
        ...(searchKeyword ? {
            OR: [
                { fileName: { contains: searchKeyword } },
                { code: { contains: searchKeyword } }
            ]
        } : {})
    };
    const { data: currentShareCodes, refetch: searchRefetch }: { data: ShareCodeWithResource, refetch: () => void } = api.shareCode.getShareCodesWithResources.useQuery(
        {
            page: currentPage,
            pageSize: pageSize,
            where: whereCondition,
        },
        {
            enabled: true,
            refetchOnWindowFocus: false,
        }
    )
    const { mutate: softDeleteShareCode } = api.shareCode.softDeleteShareCodes.useMutation({
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: getQueryKey(api.shareCode) });
        },
        onError: () => {
            message.error('删除失败')
        }
    })
    const { mutate: updateShareCode } = api.shareCode.updateShareCode.useMutation({
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: getQueryKey(api.shareCode) });
        },
        onError: () => {
            message.error('更新失败')
        }
    })
    const deletShareCode = (id: string) => {
        softDeleteShareCode({ ids: [id] })
    }
    const updateCode = (expiresAt: Date, canUseTimes: number) => {
        if (currentCodeId) updateShareCode({ id: currentCodeId, data: { expiresAt, canUseTimes } })
    }
    const [isLoading, setIsLoading] = useState(false);
    return <>
        <CodeManageContext.Provider value={{
            editForm,
            isLoading,
            currentShareCodes,
            currentPage,
            setCurrentPage,
            pageSize,
            deletShareCode,
            updateCode,
            currentCodeId,
            setCurrentCodeId,
            searchRefetch,
            setSearchKeyword,
            currentCode,
            setCurrentCode
        }}>
            {children}
        </CodeManageContext.Provider>
    </>
};

export const useCodeManageContext = () => {
    const context = useContext(CodeManageContext);
    if (!context) {
        throw new Error("useCodeManageContext must be used within a CodeManageProvider");
    }
    return context;
};