import { useEffect, useState } from "react";
import type { ReactNode } from "react";
import { fetchFields } from "./api";
import { ChecklistFieldsContext, EMPTY_CHECKLIST_FIELDS } from "./checklistFields";
import type { ChecklistFields } from "./checklistFields";

// Fetched once at app mount and held in context: the list is small, static for
// the life of the backend process, and every screen needs it (issue #37).
export function ChecklistFieldsProvider({ children }: { children: ReactNode }) {
  const [state, setState] = useState<ChecklistFields>(EMPTY_CHECKLIST_FIELDS);

  useEffect(() => {
    let cancelled = false;
    fetchFields()
      .then((fields) => {
        if (cancelled) return;
        setState({
          fields,
          names: fields.map((f) => f.name),
          labels: Object.fromEntries(fields.map((f) => [f.name, f.label])),
          loading: false,
          error: null,
        });
      })
      .catch((err) => {
        if (cancelled) return;
        setState({
          ...EMPTY_CHECKLIST_FIELDS,
          loading: false,
          error: err instanceof Error ? err.message : String(err),
        });
      });
    return () => {
      cancelled = true;
    };
  }, []);

  return (
    <ChecklistFieldsContext.Provider value={state}>{children}</ChecklistFieldsContext.Provider>
  );
}
