import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from "react";

/** Snapshot từ tab Phiếu đánh giá — dùng khi Duyệt/Từ chối ở tab mẫu DOCX / minh chứng. */
export type CouncilEvaluationSnapshot = {
  initiativeName: string;
  authorName: string;
  noveltyLevel: "high" | "medium" | "low" | null;
  effectivenessLevel: "high" | "medium" | "low" | null;
  totalScore: number;
};

type Ctx = {
  snapshot: CouncilEvaluationSnapshot | null;
  setSnapshot: (s: CouncilEvaluationSnapshot | null) => void;
};

const CouncilEvaluationSnapshotContext = createContext<Ctx | null>(null);

export function CouncilEvaluationSnapshotProvider({ children }: { children: ReactNode }) {
  const [snapshot, setSnapshot] = useState<CouncilEvaluationSnapshot | null>(null);
  const value = useMemo(() => ({ snapshot, setSnapshot }), [snapshot]);
  return (
    <CouncilEvaluationSnapshotContext.Provider value={value}>{children}</CouncilEvaluationSnapshotContext.Provider>
  );
}

export function useCouncilEvaluationSnapshotWriter() {
  const ctx = useContext(CouncilEvaluationSnapshotContext);
  const setSnapshot = ctx?.setSnapshot;
  const stable = useCallback(
    (s: CouncilEvaluationSnapshot | null) => {
      setSnapshot?.(s);
    },
    [setSnapshot],
  );
  return setSnapshot ? stable : null;
}

export function useCouncilEvaluationSnapshotReader() {
  const ctx = useContext(CouncilEvaluationSnapshotContext);
  return ctx?.snapshot ?? null;
}
