import { create } from 'zustand';
import { immer } from 'zustand/middleware/immer';
import type { ProductionPlan, PlanProcessStep, Company, Profile } from '../types';

// ========== 计划状态管理 ==========

interface PlanState {
  plans: ProductionPlan[];
  selectedPlan: ProductionPlan | null;
  planSteps: Record<string, PlanProcessStep[]>;
  loading: boolean;
  error: string | null;
}

interface PlanActions {
  setPlans: (plans: ProductionPlan[]) => void;
  addPlan: (plan: ProductionPlan) => void;
  updatePlan: (id: string, updates: Partial<ProductionPlan>) => void;
  deletePlan: (id: string) => void;
  selectPlan: (plan: ProductionPlan | null) => void;
  setPlanSteps: (planId: string, steps: PlanProcessStep[]) => void;
  updatePlanStep: (planId: string, stepId: string, updates: Partial<PlanProcessStep>) => void;
  setLoading: (loading: boolean) => void;
  setError: (error: string | null) => void;
}

export const usePlanStore = create<PlanState & PlanActions>()(
  immer((set) => ({
    plans: [],
    selectedPlan: null,
    planSteps: {},
    loading: false,
    error: null,

    setPlans: (plans) =>
      set((state) => {
        state.plans = plans;
      }),

    addPlan: (plan) =>
      set((state) => {
        state.plans.unshift(plan);
      }),

    updatePlan: (id, updates) =>
      set((state) => {
        const plan = state.plans.find((p) => p.id === id);
        if (plan) {
          Object.assign(plan, updates);
        }
      }),

    deletePlan: (id) =>
      set((state) => {
        state.plans = state.plans.filter((p) => p.id !== id);
        if (state.selectedPlan?.id === id) {
          state.selectedPlan = null;
        }
      }),

    selectPlan: (plan) =>
      set((state) => {
        state.selectedPlan = plan;
      }),

    setPlanSteps: (planId, steps) =>
      set((state) => {
        state.planSteps[planId] = steps;
      }),

    updatePlanStep: (planId, stepId, updates) =>
      set((state) => {
        const steps = state.planSteps[planId];
        if (steps) {
          const step = steps.find((s) => s.id === stepId);
          if (step) {
            Object.assign(step, updates);
          }
        }
      }),

    setLoading: (loading) =>
      set((state) => {
        state.loading = loading;
      }),

    setError: (error) =>
      set((state) => {
        state.error = error;
      }),
  }))
);

// ========== 库存状态管理 ==========

interface InventoryItem {
  id: string;
  planId: string;
  quantity: number;
  rolls: number;
  createdAt: string;
}

interface InventoryState {
  items: InventoryItem[];
  loading: boolean;
  error: string | null;
}

interface InventoryActions {
  setItems: (items: InventoryItem[]) => void;
  addItem: (item: InventoryItem) => void;
  updateItem: (id: string, updates: Partial<InventoryItem>) => void;
  deleteItem: (id: string) => void;
  setLoading: (loading: boolean) => void;
  setError: (error: string | null) => void;
}

export const useInventoryStore = create<InventoryState & InventoryActions>()(
  immer((set) => ({
    items: [],
    loading: false,
    error: null,

    setItems: (items) =>
      set((state) => {
        state.items = items;
      }),

    addItem: (item) =>
      set((state) => {
        state.items.unshift(item);
      }),

    updateItem: (id, updates) =>
      set((state) => {
        const item = state.items.find((i) => i.id === id);
        if (item) {
          Object.assign(item, updates);
        }
      }),

    deleteItem: (id) =>
      set((state) => {
        state.items = state.items.filter((i) => i.id !== id);
      }),

    setLoading: (loading) =>
      set((state) => {
        state.loading = loading;
      }),

    setError: (error) =>
      set((state) => {
        state.error = error;
      }),
  }))
);

// ========== UI 状态管理 ==========

interface UIState {
  sidebarOpen: boolean;
  modalOpen: boolean;
  modalContent: string | null;
  toast: { message: string; type: 'success' | 'error' | 'info' } | null;
}

interface UIActions {
  toggleSidebar: () => void;
  setSidebarOpen: (open: boolean) => void;
  openModal: (content: string) => void;
  closeModal: () => void;
  showToast: (message: string, type: 'success' | 'error' | 'info') => void;
  hideToast: () => void;
}

export const useUIStore = create<UIState & UIActions>()(
  immer((set) => ({
    sidebarOpen: false,
    modalOpen: false,
    modalContent: null,
    toast: null,

    toggleSidebar: () =>
      set((state) => {
        state.sidebarOpen = !state.sidebarOpen;
      }),

    setSidebarOpen: (open) =>
      set((state) => {
        state.sidebarOpen = open;
      }),

    openModal: (content) =>
      set((state) => {
        state.modalOpen = true;
        state.modalContent = content;
      }),

    closeModal: () =>
      set((state) => {
        state.modalOpen = false;
        state.modalContent = null;
      }),

    showToast: (message, type) =>
      set((state) => {
        state.toast = { message, type };
      }),

    hideToast: () =>
      set((state) => {
        state.toast = null;
      }),
  }))
);

// ========== 网络状态管理 ==========

interface NetworkState {
  isOnline: boolean;
  isSlowConnection: boolean;
  pendingRequests: number;
}

interface NetworkActions {
  setOnline: (online: boolean) => void;
  setSlowConnection: (slow: boolean) => void;
  incrementPending: () => void;
  decrementPending: () => void;
}

export const useNetworkStore = create<NetworkState & NetworkActions>()(
  immer((set) => ({
    isOnline: true,
    isSlowConnection: false,
    pendingRequests: 0,

    setOnline: (online) =>
      set((state) => {
        state.isOnline = online;
      }),

    setSlowConnection: (slow) =>
      set((state) => {
        state.isSlowConnection = slow;
      }),

    incrementPending: () =>
      set((state) => {
        state.pendingRequests++;
      }),

    decrementPending: () =>
      set((state) => {
        state.pendingRequests = Math.max(0, state.pendingRequests - 1);
      }),
  }))
);
