import React, {
    createContext,
    ReactNode,
    useContext,
    useMemo,
    useState,
} from "react";
// import { useDebounce } from "use-debounce";
import { Form, FormInstance } from 'antd';
import { api } from "@nice/client";
import toast from "react-hot-toast";

interface AssessmentStandardContextType {
    form: FormInstance;
    sportProjectList: {
        id: string;
        name: string;
        unit: string;
        deletedAt?: string | null;
    }[];
    sportProjectLoading: boolean;
    ageRanges: { start: number; end: number; label: string; }[];
    records: { score: number, standards: number[] }[];
    isAgeModalVisible: boolean;
    isScoreModalVisible: boolean;
    showAgeModal: () => void;
    handleAgeOk: (values: any) => void;
    handleAgeCancel: () => void;
    showScoreModal: () => void;
    handleScoreOk: (values: any) => void;
    handleScoreCancel: () => void;
    setRecords: (records: { score: number, standards: number[] }[]) => void;
    setIsAgeModalVisible: (isAgeModalVisible: boolean) => void;
    setIsScoreModalVisible: (isScoreModalVisible: boolean) => void;
    ageForm: FormInstance;
    scoreForm: FormInstance;
    setAgeRanges: (ageRanges: { start: number; end: number; label: string; }[]) => void;
    isStandardCreate: boolean;
    setIsStandardCreate: (isStandardCreate: boolean) => void;
}

const AssessmentStandardContext = createContext<AssessmentStandardContextType | null>(null);
interface AssessmentStandardProviderProps {
    children: ReactNode;
}

export function AssessmentStandardProvider({ children }: AssessmentStandardProviderProps) {
    const [form] = Form.useForm();
    const [ageForm] = Form.useForm();
    const [scoreForm] = Form.useForm();
    const { data: sportProjectList, isLoading: sportProjectLoading } = api.sportProject.findMany.useQuery()
    const [ageRanges, setAgeRanges] = useState<{ start: number; end: number; label: string; }[]>([]);
    const [records, setRecords] = useState<{ score: number, standards: number[] }[]>([]);
    const [isAgeModalVisible, setIsAgeModalVisible] = useState(false);
    const [isScoreModalVisible, setIsScoreModalVisible] = useState(false);
    const [isStandardCreate, setIsStandardCreate] = useState(true);
    // 显示年龄范围模态框
    const showAgeModal = () => {
        setIsAgeModalVisible(true);
    };
    // 处理年龄范围模态框确定
    const handleAgeOk = (values: any) => {
        console.log('values', values)
        const { start, end } = values;
        if (end && start == end) {
            toast.error("年龄范围不能相同");
            return;
        }
        //年龄校验
        const isOverlap = ageRanges.some(range => {
            if (end) {
                return (start >= range.start && start <= (range.end || Infinity)) ||
                    (end >= range.start && end <= (range.end || Infinity)) ||
                    (start <= range.start && end >= (range.end || Infinity));
            } else {
                return start >= range.start && start <= (range.end || Infinity);
            }
        });
        if (isOverlap) {
            toast.error("年龄范围不能与已存在的范围重叠");
            return;
        }
        const newRange = {
            start,
            end,
            label: end ? `${start}-${end}岁` : `${start}岁以上`,
        };
        setAgeRanges([...ageRanges, newRange]);
        setIsAgeModalVisible(false);
    };
    // 处理年龄范围模态框取消
    const handleAgeCancel = () => {
        setIsAgeModalVisible(false);
    };

    // 显示分数标准模态框
    const showScoreModal = () => {
        setIsScoreModalVisible(true);
    };
    // 处理分数标准模态框确定
    const handleScoreOk = async (values: any) => {
        const { score, standards } = values;
        console.log(values)
        const standardsArray = Object.keys(values)
            .filter(key => key.startsWith('standards_'))
            .map(key => values[key]);
        setRecords([...records, { score, standards: standardsArray }]);
        setIsScoreModalVisible(false);
    };

    // 处理分数标准模态框取消
    const handleScoreCancel = () => {
        setIsScoreModalVisible(false);
    };
    return (
        <AssessmentStandardContext.Provider
            value={{
                form,
                sportProjectList: sportProjectList?.map((item) => ({
                    id: item.id,
                    name: item.name,
                    unit: item.unit,
                    deletedAt: item.deletedAt
                })),
                sportProjectLoading,
                ageRanges,
                records,
                isAgeModalVisible,
                isScoreModalVisible,
                setIsAgeModalVisible,
                setIsScoreModalVisible,
                showAgeModal,
                handleAgeOk,
                handleAgeCancel,
                showScoreModal,
                handleScoreOk,
                handleScoreCancel,
                setRecords,
                ageForm,
                scoreForm,
                setAgeRanges,
                isStandardCreate,
                setIsStandardCreate
            }}>
            {children}
        </AssessmentStandardContext.Provider>
    );
}
export const useAssessmentStandardContext = () => {
    const context = useContext(AssessmentStandardContext);
    if (!context) {
        throw new Error("useAssessmentStandardContext must be used within AssessmentStandardProvider");
    }
    return context;
};
