import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import { DEFAULT_DEVICE_IP, DEFAULT_TCP_PORT } from '../protocol/constants';
import type { ConnectionStatus } from '../protocol/types';
import { fileStorage } from '../utils/storage';

interface ConnectionState {
  status:       ConnectionStatus;
  host:         string;
  port:         number;
  lastError:    string;
  modalVisible: boolean;
  setStatus:    (s: ConnectionStatus) => void;
  setHost:      (h: string) => void;
  setPort:      (p: number) => void;
  setError:     (e: string) => void;
  showModal:    () => void;
  hideModal:    () => void;
}

export const useConnectionStore = create<ConnectionState>()(
  persist(
    (set) => ({
      status:       'disconnected',
      host:         DEFAULT_DEVICE_IP,
      port:         DEFAULT_TCP_PORT,
      lastError:    '',
      modalVisible: false,
      setStatus:    (status)     => set({ status }),
      setHost:      (host)       => set({ host }),
      setPort:      (port)       => set({ port }),
      setError:     (lastError)  => set({ lastError, status: 'error' }),
      showModal:    ()           => set({ modalVisible: true }),
      hideModal:    ()           => set({ modalVisible: false }),
    }),
    {
      name: 'connection-config',
      storage: createJSONStorage(() => fileStorage),
      partialize: (state) => ({ host: state.host, port: state.port }),
    },
  ),
);
