import { create } from 'zustand';
import { persist } from 'zustand/middleware';

import type { WidgetItem } from '@/components/dashboard/widget-grid';

/** Default widget layout for new users */
const DEFAULT_WIDGETS: WidgetItem[] = [
  { id: 'welcome-1', type: 'welcome', colSpan: 2 },
  { id: 'clock-1', type: 'clock' },
  { id: 'stats-1', type: 'stats', settings: { statKey: 'presentToday' } },
  { id: 'stats-2', type: 'stats', settings: { statKey: 'openTasks' } },
  { id: 'stats-3', type: 'stats', settings: { statKey: 'upcomingMeetings' } },
  { id: 'quickActions-1', type: 'quickActions', rowSpan: 2 },
  { id: 'activity-1', type: 'activity', colSpan: 2, rowSpan: 2 },
  { id: 'calendar-1', type: 'calendar', rowSpan: 2 },
];

interface DashboardState {
  /** Array of widget items in the current layout */
  widgets: WidgetItem[];

  /** Whether the dashboard is in edit mode */
  isEditing: boolean;

  /** Set the widgets array */
  setWidgets: (widgets: WidgetItem[]) => void;

  /** Add a new widget */
  addWidget: (type: string, settings?: Record<string, unknown>) => void;

  /** Remove a widget by ID */
  removeWidget: (id: string) => void;

  /** Update widget settings */
  updateWidgetSettings: (id: string, settings: Record<string, unknown>) => void;

  /** Toggle edit mode */
  toggleEditMode: () => void;

  /** Set edit mode */
  setEditMode: (editing: boolean) => void;

  /** Reset to default layout */
  resetToDefault: () => void;
}

/**
 * Generate a unique widget ID
 */
function generateWidgetId(type: string): string {
  return `${type}-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;
}

/**
 * Dashboard store for managing widget layout and state
 * Persists widget layout to localStorage
 */
export const useDashboardStore = create<DashboardState>()(
  persist(
    (set, get) => ({
      widgets: DEFAULT_WIDGETS,
      isEditing: false,

      setWidgets: (widgets) => set({ widgets }),

      addWidget: (type, settings) => {
        const newWidget: WidgetItem = {
          id: generateWidgetId(type),
          type,
          settings,
        };

        set((state) => ({
          widgets: [...state.widgets, newWidget],
        }));
      },

      removeWidget: (id) => {
        set((state) => ({
          widgets: state.widgets.filter((w) => w.id !== id),
        }));
      },

      updateWidgetSettings: (id, settings) => {
        set((state) => ({
          widgets: state.widgets.map((w) =>
            w.id === id ? { ...w, settings: { ...w.settings, ...settings } } : w
          ),
        }));
      },

      toggleEditMode: () => set((state) => ({ isEditing: !state.isEditing })),

      setEditMode: (editing) => set({ isEditing: editing }),

      resetToDefault: () => set({ widgets: DEFAULT_WIDGETS }),
    }),
    {
      name: 'tos-dashboard-layout',
      partialize: (state) => ({ widgets: state.widgets }),
    }
  )
);
