// FE-OP002: 前端状态管理优化
import { createStore, combineReducers, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { createLogger } from 'redux-logger';

// 定义状态类型
interface AppState {
  user: UserState;
  products: ProductState;
  orders: OrderState;
  loading: boolean;
  error: string | null;
}

interface UserState {
  isLoggedIn: boolean;
  userInfo: any;
  token: string | null;
}

interface ProductState {
  list: any[];
  selected: any | null;
  loading: boolean;
}

interface OrderState {
  list: any[];
  selected: any | null;
  loading: boolean;
}

// 定义初始状态
const initialState: AppState = {
  user: {
    isLoggedIn: false,
    userInfo: null,
    token: null,
  },
  products: {
    list: [],
    selected: null,
    loading: false,
  },
  orders: {
    list: [],
    selected: null,
    loading: false,
  },
  loading: false,
  error: null,
};

// 定义action类型
const SET_LOADING = 'SET_LOADING';
const SET_ERROR = 'SET_ERROR';
const CLEAR_ERROR = 'CLEAR_ERROR';

// User actions
const SET_USER = 'SET_USER';
const LOGOUT = 'LOGOUT';

// Product actions
const SET_PRODUCTS = 'SET_PRODUCTS';
const SET_SELECTED_PRODUCT = 'SET_SELECTED_PRODUCT';
const SET_PRODUCTS_LOADING = 'SET_PRODUCTS_LOADING';

// Order actions
const SET_ORDERS = 'SET_ORDERS';
const SET_SELECTED_ORDER = 'SET_SELECTED_ORDER';
const SET_ORDERS_LOADING = 'SET_ORDERS_LOADING';

// Action creators
export const setLoading = (loading: boolean) => ({ type: SET_LOADING, payload: loading });
export const setError = (error: string) => ({ type: SET_ERROR, payload: error });
export const clearError = () => ({ type: CLEAR_ERROR });

// User action creators
export const setUser = (userInfo: any, token: string) => ({ type: SET_USER, payload: { userInfo, token } });
export const logout = () => ({ type: LOGOUT });

// Product action creators
export const setProducts = (products: any[]) => ({ type: SET_PRODUCTS, payload: products });
export const setSelectedProduct = (product: any | null) => ({ type: SET_SELECTED_PRODUCT, payload: product });
export const setProductsLoading = (loading: boolean) => ({ type: SET_PRODUCTS_LOADING, payload: loading });

// Order action creators
export const setOrders = (orders: any[]) => ({ type: SET_ORDERS, payload: orders });
export const setSelectedOrder = (order: any | null) => ({ type: SET_SELECTED_ORDER, payload: order });
export const setOrdersLoading = (loading: boolean) => ({ type: SET_ORDERS_LOADING, payload: loading });

// Reducers
const userReducer = (state = initialState.user, action: any) => {
  switch (action.type) {
    case SET_USER:
      return {
        ...state,
        isLoggedIn: true,
        userInfo: action.payload.userInfo,
        token: action.payload.token,
      };
    case LOGOUT:
      return initialState.user;
    default:
      return state;
  }
};

const productsReducer = (state = initialState.products, action: any) => {
  switch (action.type) {
    case SET_PRODUCTS:
      return {
        ...state,
        list: action.payload,
      };
    case SET_SELECTED_PRODUCT:
      return {
        ...state,
        selected: action.payload,
      };
    case SET_PRODUCTS_LOADING:
      return {
        ...state,
        loading: action.payload,
      };
    default:
      return state;
  }
};

const ordersReducer = (state = initialState.orders, action: any) => {
  switch (action.type) {
    case SET_ORDERS:
      return {
        ...state,
        list: action.payload,
      };
    case SET_SELECTED_ORDER:
      return {
        ...state,
        selected: action.payload,
      };
    case SET_ORDERS_LOADING:
      return {
        ...state,
        loading: action.payload,
      };
    default:
      return state;
  }
};

const appReducer = (state = initialState, action: any) => {
  switch (action.type) {
    case SET_LOADING:
      return {
        ...state,
        loading: action.payload,
      };
    case SET_ERROR:
      return {
        ...state,
        error: action.payload,
      };
    case CLEAR_ERROR:
      return {
        ...state,
        error: null,
      };
    default:
      return state;
  }
};

// 组合reducers
const rootReducer = combineReducers({
  user: userReducer,
  products: productsReducer,
  orders: ordersReducer,
  app: appReducer,
});

// 中间件
const middleware = [thunk];

// 开发环境添加logger
if (process.env.NODE_ENV === 'development') {
  const logger = createLogger();
  middleware.push(logger);
}

// 创建store
const store = createStore(rootReducer, applyMiddleware(...middleware));

export type RootState = ReturnType<typeof rootReducer>;
export default store;
