import { create } from 'zustand';
import type {
  WebUsageSummary,
  WebNotification,
  WebViewKey,
  WebImageWorkbenchTool,
} from '../types';
import type { ServerConnectionHealth } from '../api/serverConnection';
import type { TemplateCase } from '../features/ecommerce/ecommerceTemplates';

interface AppState {
  usage: WebUsageSummary;
  runtimeNotifications: WebNotification[];
  serverNotifications: WebNotification[];
  activeView: WebViewKey;
  workspaceExpanded: boolean;
  imageWorkbenchTool: WebImageWorkbenchTool;
  pendingEcommerceTemplate: TemplateCase | null;
  backendHealth: ServerConnectionHealth;
}

interface AppActions {
  setUsage: (usage: WebUsageSummary) => void;
  pushNotification: (notification: Omit<WebNotification, 'id' | 'createdAt' | 'isRead'>) => void;
  setRuntimeNotifications: (notifications: WebNotification[]) => void;
  setServerNotifications: (notifications: WebNotification[]) => void;
  setView: (view: WebViewKey) => void;
  setWorkspaceExpanded: (expanded: boolean) => void;
  setImageWorkbenchTool: (tool: WebImageWorkbenchTool) => void;
  setPendingEcommerceTemplate: (template: TemplateCase | null) => void;
  setBackendHealth: (health: ServerConnectionHealth) => void;
  markNotificationRead: (id: string, isRead?: boolean) => void;
  markAllNotificationsRead: () => void;
  clearAppState: () => void;
}

const emptyUsageSummary: WebUsageSummary = {
  balanceCents: 0,
  imageUsed: 0,
  videoUsed: 0,
  textUsed: 0,
  source: 'preview',
};

const initialState: AppState = {
  usage: emptyUsageSummary,
  runtimeNotifications: [],
  serverNotifications: [],
  activeView: 'home',
  workspaceExpanded: false,
  imageWorkbenchTool: 'workbench',
  pendingEcommerceTemplate: null,
  backendHealth: {
    state: 'checking',
    baseUrl: '',
    checkedAt: new Date().toISOString(),
  },
};

export const useAppStore = create<AppState & AppActions>((set) => ({
  ...initialState,

  setUsage: (usage) => set({ usage }),

  pushNotification: (notification) => set((state) => ({
    runtimeNotifications: [
      {
        ...notification,
        id: `notice-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,
        createdAt: new Date().toISOString(),
        isRead: false,
      },
      ...state.runtimeNotifications,
    ].slice(0, 30),
  })),

  setRuntimeNotifications: (notifications) => set({ runtimeNotifications: notifications }),

  setServerNotifications: (notifications) => set({ serverNotifications: notifications }),

  setView: (view) => set({ activeView: view }),

  setWorkspaceExpanded: (expanded) => set({ workspaceExpanded: expanded }),

  setImageWorkbenchTool: (tool) => set({ imageWorkbenchTool: tool }),

  setPendingEcommerceTemplate: (template) => set({ pendingEcommerceTemplate: template }),

  setBackendHealth: (health) => set({ backendHealth: health }),

  markNotificationRead: (id, isRead = true) => set((state) => ({
    serverNotifications: state.serverNotifications.map((item) =>
      item.id === id ? { ...item, isRead, readAt: isRead ? new Date().toISOString() : null } : item
    ),
  })),

  markAllNotificationsRead: () => set((state) => ({
    serverNotifications: state.serverNotifications.map((item) => ({
      ...item,
      isRead: true,
      readAt: new Date().toISOString(),
    })),
  })),

  clearAppState: () => set({
    ...initialState,
    usage: emptyUsageSummary,
    runtimeNotifications: [],
    serverNotifications: [],
  }),
}));
