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

const TransformContext = createContext<{
  position: { x: number; y: number };
  scale: number;
  setPosition: React.Dispatch<React.SetStateAction<{ x: number; y: number }>>;
  setScale: React.Dispatch<React.SetStateAction<number>>;
  screenCenter?: { x: number; y: number };
  setScreenCenter: React.Dispatch<
    React.SetStateAction<{ x: number; y: number } | undefined>
  >;
  isAutoMode: boolean;
  setIsAutoMode: React.Dispatch<React.SetStateAction<boolean>>;
  userActivityTimestamp: number;
  updateUserActivity: () => void;
  autoModeStartTimestamp: number | null;
  setAutoModeStartTimestamp: React.Dispatch<
    React.SetStateAction<number | null>
  >;
}>({
  position: { x: 0, y: 0 },
  scale: 1,
  setPosition: () => {},
  setScale: () => {},
  screenCenter: undefined,
  setScreenCenter: () => {},
  isAutoMode: false,
  setIsAutoMode: () => {},
  userActivityTimestamp: Date.now(),
  updateUserActivity: () => {},
  autoModeStartTimestamp: null,
  setAutoModeStartTimestamp: () => {},
});

export const TransformProvider = ({ children }: { children: ReactNode }) => {
  const [position, setPosition] = useState({ x: 0, y: 0 });
  const [scale, setScale] = useState(1);
  const [screenCenter, setScreenCenter] = useState<{ x: number; y: number }>();
  const [isAutoMode, setIsAutoMode] = useState(false);
  const [userActivityTimestamp, setUserActivityTimestamp] = useState(
    Date.now()
  );

  const [autoModeStartTimestamp, setAutoModeStartTimestamp] = useState<
    number | null
  >(null);

  const updateUserActivity = useCallback(() => {
    setUserActivityTimestamp(Date.now());
    // Убираем автоматическое отключение авто режима - это будет делаться в InfiniteCanvas
  }, []);

  const value = {
    position,
    scale,
    setPosition,
    setScale,
    screenCenter,
    setScreenCenter,
    isAutoMode,
    setIsAutoMode,
    userActivityTimestamp,
    updateUserActivity,
    autoModeStartTimestamp,
    setAutoModeStartTimestamp,
  };

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

export const useTransform = () => {
  const context = useContext(TransformContext);
  if (!context) {
    throw new Error("useTransform must be used within a TransformProvider");
  }
  return context;
};
