import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import type {
  ModuleId,
  User,
  ChatMessage,
  Lead,
  Visitor,
  DashboardMetrics,
  LeadVelocityData,
  Unit,
  SystemStatus,
  VelocityNotification,
} from '@/types';


// Auth State
interface AuthState {
  isAuthenticated: boolean;
  user: User | null;
  login: (user: User) => void;
  logout: () => void;
}

// Navigation State
interface NavigationState {
  activeModule: ModuleId;
  sidebarExpanded: boolean;
  setActiveModule: (module: ModuleId) => void;
  toggleSidebar: () => void;
  setSidebarExpanded: (expanded: boolean) => void;
}

// Oracle State
interface OracleState {
  leads: Lead[];
  activeLeadId: string | null;
  messages: Record<string, ChatMessage[]>;
  isOracleThinking: boolean;
  setLeads: (leads: Lead[]) => void;
  replaceMessages: (messages: Record<string, ChatMessage[]>) => void;
  setActiveLead: (leadId: string | null) => void;
  addMessage: (leadId: string, message: ChatMessage) => void;
  setOracleThinking: (thinking: boolean) => void;
  markLeadAsRead: (leadId: string) => void;
}

// Sentinel State
interface SentinelState {
  visitors: Visitor[];
  isAlertActive: boolean;
  alertMessage: string;
  addVisitor: (visitor: Visitor) => void;
  removeVisitor: (visitorId: string) => void;
  triggerAlert: (message: string) => void;
  clearAlert: () => void;
}

// Dashboard State
interface DashboardState {
  metrics: DashboardMetrics;
  velocityData: LeadVelocityData[];
  updateMetrics: (metrics: Partial<DashboardMetrics>) => void;
  setVelocityData: (data: LeadVelocityData[]) => void;
  addVelocityDataPoint: (data: LeadVelocityData) => void;
}

// Inventory State
interface InventoryState {
  units: Unit[];
  selectedUnitId: string | null;
  filterStatus: Unit['status'] | 'all';
  setUnits: (units: Unit[]) => void;
  setSelectedUnit: (unitId: string | null) => void;
  setFilterStatus: (status: Unit['status'] | 'all') => void;
}

// System State
interface SystemState {
  status: SystemStatus;
  updateStatus: (status: Partial<SystemStatus>) => void;
}

// Notification State (Active Notification Center)
interface NotificationState {
  notifications: VelocityNotification[];
  unreadCount: number;
  addNotification: (notification: Omit<VelocityNotification, 'id' | 'isRead' | 'timestamp'>) => void;
  markAllRead: () => void;
  markAsRead: (id: string) => void;
  clearNotifications: () => void;
}


// Combined Store
interface StoreState extends
  AuthState,
  NavigationState,
  OracleState,
  SentinelState,
  DashboardState,
  InventoryState,
  SystemState,
  NotificationState { }

export const useStore = create<StoreState>()(
  persist(
    (set) => ({
      // Auth State
      isAuthenticated: false,
      user: null,
      login: (user) => set({ isAuthenticated: true, user }),
      logout: () => set({ isAuthenticated: false, user: null }),

      // Navigation State
      activeModule: 'dashboard',
      sidebarExpanded: false,
      setActiveModule: (module) => set({ activeModule: module }),
      toggleSidebar: () => set((state) => ({ sidebarExpanded: !state.sidebarExpanded })),
      setSidebarExpanded: (expanded) => set({ sidebarExpanded: expanded }),

      // Oracle State
      leads: [],
      activeLeadId: null,
      messages: {},
      isOracleThinking: false,
      setLeads: (leads) => set({ leads }),
      replaceMessages: (messages) => set({ messages }),
      setActiveLead: (leadId) => set({ activeLeadId: leadId }),
      addMessage: (leadId, message) => set((state) => ({
        messages: {
          ...state.messages,
          [leadId]: [...(state.messages[leadId] || []), message],
        },
      })),
      setOracleThinking: (thinking) => set({ isOracleThinking: thinking }),
      markLeadAsRead: (leadId) => set((state) => ({
        leads: state.leads.map((lead) =>
          lead.id === leadId ? { ...lead, unreadCount: 0 } : lead
        ),
      })),

      // Sentinel State
      visitors: [],
      isAlertActive: false,
      alertMessage: '',
      addVisitor: (visitor) => set((state) => ({
        visitors: [...state.visitors, visitor]
      })),
      removeVisitor: (visitorId) => set((state) => ({
        visitors: state.visitors.filter((v) => v.id !== visitorId),
      })),
      triggerAlert: (message) => set({ isAlertActive: true, alertMessage: message }),
      clearAlert: () => set({ isAlertActive: false, alertMessage: '' }),

      // Dashboard State
      metrics: {
        activeVisitors: 0,
        todayLeads: 0,
        closedDeals: 0,
        conversionRate: 0,
        sentiment: 0,
        systemHealth: {
          cpu: 0,
          gpu: 0,
          memory: 0,
          temperature: 0,
        },
      },
      velocityData: [],
      updateMetrics: (metrics) => set((state) => ({
        metrics: { ...state.metrics, ...metrics },
      })),
      setVelocityData: (data) => set({ velocityData: data }),
      addVelocityDataPoint: (data) => set((state) => ({
        velocityData: [...state.velocityData.slice(1), data],
      })),

      // Inventory State
      units: [],
      selectedUnitId: null,
      filterStatus: 'all',
      setUnits: (units) => set({ units }),
      setSelectedUnit: (unitId) => set({ selectedUnitId: unitId }),
      setFilterStatus: (status) => set({ filterStatus: status }),

      // System State
      status: {
        isConnected: false,
        serverStatus: 'syncing',
        lastSync: new Date(),
        version: '2.2.0 CRM',
      },
      updateStatus: (status) => set((state) => ({
        status: { ...state.status, ...status },
      })),

      // Notification State
      notifications: [],
      unreadCount: 0,
      addNotification: (notif) => set((state) => {
        const newNotif: VelocityNotification = {
          ...notif,
          id: `notif-${Date.now()}-${Math.random().toString(36).slice(2)}`,
          isRead: false,
          timestamp: new Date(),
        };
        const updated = [newNotif, ...state.notifications].slice(0, 50);
        return {
          notifications: updated,
          unreadCount: updated.filter((n) => !n.isRead).length,
        };
      }),
      markAllRead: () => set((state) => ({
        notifications: state.notifications.map((n) => ({ ...n, isRead: true })),
        unreadCount: 0,
      })),
      markAsRead: (id) => set((state) => {
        const updated = state.notifications.map((n) =>
          n.id === id ? { ...n, isRead: true } : n
        );
        return {
          notifications: updated,
          unreadCount: updated.filter((n) => !n.isRead).length,
        };
      }),
      clearNotifications: () => set({ notifications: [], unreadCount: 0 }),

    }),
    {
      name: 'velocity-webos-storage',
      partialize: (state) => ({
        user: state.user,
        activeModule: state.activeModule,
      }),
    }
  )
);
