import { create } from "zustand";
import { immer } from "zustand/middleware/immer";

interface MachineStore {
  machines: MachineStatus[];

  addMachine: (productUuid: string, machine: MachineEventSchema) => void;
  removeMachine: (modelUuid: string) => void;
  updateMachine: (
    modelUuid: string,
    updates: Partial<Omit<MachineStatus, "modelUuid" | "productUuid">>
  ) => void;
  clearMachines: () => void;

  addCurrentAction: (
    modelUuid: string,
    actionUuid: string,
    materialType: string,
    materialId: string
  ) => void;
  removeCurrentAction: (modelUuid: string) => void;

  setMachineActive: (modelUuid: string, isActive: boolean) => void;
  setMachineState: (
    modelUuid: string,
    newState: MachineStatus["state"]
  ) => void;

  incrementActiveTime: (modelUuid: string, incrementBy: number) => void;
  incrementIdleTime: (modelUuid: string, incrementBy: number) => void;
  resetTime: (modelUuid: string) => void;

  getMachineById: (modelUuid: string) => MachineStatus | undefined;
  getMachinesByProduct: (productUuid: string) => MachineStatus[];
  getMachinesBystate: (state: string) => MachineStatus[];
  getActiveMachines: () => MachineStatus[];
  getIdleMachines: () => MachineStatus[];
}

export const createMachineStore = () => {
  return create<MachineStore>()(
    immer((set, get) => ({
      machines: [],

      addMachine: (productUuid, machine) => {
        set((state) => {
          const exists = state.machines.some(
            (m) => m.modelUuid === machine.modelUuid
          );
          if (!exists) {
            state.machines.push({
              ...machine,
              productUuid,
              isActive: false,
              idleTime: 0,
              activeTime: 0,
              state: "idle",
            });
          }
        });
      },

      removeMachine: (modelUuid) => {
        set((state) => {
          state.machines = state.machines.filter(
            (m) => m.modelUuid !== modelUuid
          );
        });
      },

      updateMachine: (modelUuid, updates) => {
        set((state) => {
          const machine = state.machines.find((m) => m.modelUuid === modelUuid);
          if (machine) {
            Object.assign(machine, updates);
          }
        });
      },

      clearMachines: () => {
        set((state) => {
          state.machines = [];
        });
      },

      addCurrentAction: (modelUuid, actionUuid, materialType, materialId) => {
        set((state) => {
          const armBot = state.machines.find((a) => a.modelUuid === modelUuid);
          if (armBot) {
            const action = armBot.point.action;
            if (action) {
              armBot.currentAction = {
                actionUuid: actionUuid,
                actionName: action.actionName,
                materialType: materialType,
                materialId: materialId,
              };
            }
          }
        });
      },

      removeCurrentAction: (modelUuid) => {
        set((state) => {
          const armBot = state.machines.find((a) => a.modelUuid === modelUuid);
          if (armBot) {
            armBot.currentAction = undefined;
          }
        });
      },

      setMachineActive: (modelUuid, isActive) => {
        set((state) => {
          const machine = state.machines.find((m) => m.modelUuid === modelUuid);
          if (machine) {
            machine.isActive = isActive;
          }
        });
      },

      setMachineState: (modelUuid, newState) => {
        set((state) => {
          const machine = state.machines.find((m) => m.modelUuid === modelUuid);
          if (machine) {
            machine.state = newState;
          }
        });
      },

      incrementActiveTime: (modelUuid, incrementBy) => {
        set((state) => {
          const machine = state.machines.find((m) => m.modelUuid === modelUuid);
          if (machine) {
            machine.activeTime += incrementBy;
          }
        });
      },

      incrementIdleTime: (modelUuid, incrementBy) => {
        set((state) => {
          const machine = state.machines.find((m) => m.modelUuid === modelUuid);
          if (machine) {
            machine.idleTime += incrementBy;
          }
        });
      },
      resetTime: (modelUuid) => {
        set((state) => {
          const machine = state.machines.find((m) => m.modelUuid === modelUuid);
          if (machine) {
            machine.activeTime = 0;
            machine.idleTime = 0;
          }
        });
      },

      getMachineById: (modelUuid) => {
        return get().machines.find((m) => m.modelUuid === modelUuid);
      },

      getMachinesByProduct: (productUuid) => {
        return get().machines.filter((m) => m.productUuid === productUuid);
      },

      getMachinesBystate: (state) => {
        return get().machines.filter((m) => m.state === state);
      },

      getActiveMachines: () => {
        return get().machines.filter((m) => m.isActive);
      },

      getIdleMachines: () => {
        return get().machines.filter((m) => !m.isActive && m.state === "idle");
      },
    }))
  )
}

export type MachineStoreType = ReturnType<typeof createMachineStore>;
