import { create } from 'zustand';
import { devtools } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
import { Car } from '../types/car';
import { Job } from '../types/job';
import { createSelectors } from './createSelectors';

interface ActiveSelectionState {
  car?: Car;
  work?: Job;
  mode: 'live' | 'info' | null;
  selectedWork?: Job;
  selectedCar?: Car;
  setCar: (car: Car | null) => void;
  setWork: (work: Job | null) => void;
  setMode: (mode: 'live' | 'info' | null) => void;
  toLiveMode: (car: Car) => void;
  closeLiveMode: () => void;
  reset: () => void;
  setSelectedWork: (work: Job | null) => void;
  setSelectedCar: (car: Car | null) => void;
}

export const useActiveSelectionStoreBase = create<ActiveSelectionState>()(
  devtools(
    immer((set) => ({
      car: undefined,
      work: undefined,
      mode: 'info',
      selectedWork: undefined,
      selectedCar: undefined,
      setCar: (car) => set(() => ({ car, work: undefined })),
      setWork: (work) => set(() => ({ work, car: undefined })),
      setMode: (mode) => set(() => ({ mode })),
      toLiveMode: (car: Car) =>
        set(() => ({ car, work: undefined, mode: 'live' })),
      closeLiveMode: () =>
        set({
          car: undefined,
          work: undefined,
          mode: 'info',
        }),
      reset: () => set(() => ({ car: undefined, work: undefined })),
      setSelectedWork: (work) => set(() => ({ selectedWork: work })),
      setSelectedCar: (car) => set(() => ({ selectedCar: car })),
    })),
    {
      name: 'active-selection-storage',
    },
  ),
);

export const useActiveSelectionStore = createSelectors(
  useActiveSelectionStoreBase,
);
