import { UserResponse, CreateUserDto, UpdateUserDto, Role } from '@goodgo/types';
import { create } from 'zustand';
import { devtools } from 'zustand/middleware';

import {
  getUsers,
  getUser,
  createUser,
  updateUser,
  deleteUser,
  bulkDeleteUsers,
  bulkUpdateUserRoles,
  GetUsersParams,
  GetUsersResponse
} from '../lib/api/users';

/**
 * EN: Users store state interface
 * VI: Interface trạng thái users store
 */
interface UsersState {
  /** EN: Paginated users list / VI: Danh sách users phân trang */
  users: UserResponse[];
  /** EN: Single user data for detail view / VI: Dữ liệu user đơn lẻ cho view chi tiết */
  currentUser: UserResponse | null;
  /** EN: Pagination metadata / VI: Metadata phân trang */
  pagination: GetUsersResponse['pagination'] | null;
  /** EN: Loading state for list operations / VI: Trạng thái loading cho operations list */
  isLoading: boolean;
  /** EN: Loading state for single user operations / VI: Trạng thái loading cho operations single user */
  isLoadingUser: boolean;
  /** EN: Error message if any operation fails / VI: Thông báo lỗi nếu có operation thất bại */
  error: string | null;

  /** EN: Fetch paginated users list / VI: Lấy danh sách users phân trang */
  fetchUsers: (params?: GetUsersParams) => Promise<void>;
  /** EN: Fetch single user by ID / VI: Lấy user đơn lẻ theo ID */
  fetchUser: (id: string) => Promise<void>;
  /** EN: Create new user / VI: Tạo user mới */
  createUser: (payload: CreateUserDto) => Promise<UserResponse>;
  /** EN: Update existing user / VI: Cập nhật user hiện có */
  updateUser: (id: string, payload: UpdateUserDto) => Promise<UserResponse>;
  /** EN: Delete user by ID / VI: Xóa user theo ID */
  deleteUser: (id: string) => Promise<void>;
  /** EN: Bulk delete multiple users / VI: Xóa nhiều users cùng lúc */
  bulkDeleteUsers: (ids: string[]) => Promise<void>;
  /** EN: Bulk update user roles / VI: Cập nhật vai trò cho nhiều users */
  bulkUpdateUserRoles: (updates: Array<{ id: string; role: Role }>) => Promise<void>;
  /** EN: Clear current user data / VI: Xóa dữ liệu current user */
  clearCurrentUser: () => void;
  /** EN: Clear error state / VI: Xóa trạng thái lỗi */
  clearError: () => void;
  /** EN: Reset store to initial state / VI: Reset store về trạng thái ban đầu */
  reset: () => void;
}

/**
 * EN: Initial state for users store
 * VI: Trạng thái ban đầu cho users store
 */
const initialState = {
  users: [],
  currentUser: null,
  pagination: null,
  isLoading: false,
  isLoadingUser: false,
  error: null,
};

/**
 * EN: Zustand store for users state management
 * VI: Zustand store để quản lý trạng thái users
 *
 * Features:
 * - Paginated users list management
 * - Single user operations (CRUD)
 * - Bulk operations support
 * - Loading and error states
 * - DevTools integration for debugging
 */
export const useUsersStore = create<UsersState>()(
  devtools(
    (set, get) => ({
      ...initialState,

      /**
       * EN: Fetch paginated users list
       * VI: Lấy danh sách users phân trang
       */
      fetchUsers: async (params = {}) => {
        set({ isLoading: true, error: null });

        try {
          const response = await getUsers(params);
          set({
            users: response.data,
            pagination: response.pagination,
            isLoading: false,
          });
        } catch (error: any) {
          const errorMessage = error?.response?.data?.message || error?.message || 'Failed to fetch users';
          set({
            error: errorMessage,
            isLoading: false,
            users: [],
            pagination: null,
          });
          throw error;
        }
      },

      /**
       * EN: Fetch single user by ID
       * VI: Lấy user đơn lẻ theo ID
       */
      fetchUser: async (id: string) => {
        set({ isLoadingUser: true, error: null });

        try {
          const user = await getUser(id);
          set({
            currentUser: user,
            isLoadingUser: false,
          });
        } catch (error: any) {
          const errorMessage = error?.response?.data?.message || error?.message || 'Failed to fetch user';
          set({
            error: errorMessage,
            isLoadingUser: false,
            currentUser: null,
          });
          throw error;
        }
      },

      /**
       * EN: Create new user
       * VI: Tạo user mới
       */
      createUser: async (payload: CreateUserDto) => {
        set({ isLoadingUser: true, error: null });

        try {
          const newUser = await createUser(payload);

          // Add to users list if we have one
          const { users, pagination } = get();
          if (users.length > 0 && pagination) {
            set({
              users: [newUser, ...users.slice(0, -1)], // Add to beginning, remove last to maintain page size
              isLoadingUser: false,
            });
          } else {
            set({ isLoadingUser: false });
          }

          return newUser;
        } catch (error: any) {
          const errorMessage = error?.response?.data?.message || error?.message || 'Failed to create user';
          set({
            error: errorMessage,
            isLoadingUser: false,
          });
          throw error;
        }
      },

      /**
       * EN: Update existing user
       * VI: Cập nhật user hiện có
       */
      updateUser: async (id: string, payload: UpdateUserDto) => {
        set({ isLoadingUser: true, error: null });

        try {
          const updatedUser = await updateUser(id, payload);

          // Update in users list if present
          const { users } = get();
          const updatedUsers = users.map(user =>
            user.id === id ? updatedUser : user
          );

          set({
            users: updatedUsers,
            currentUser: updatedUser,
            isLoadingUser: false,
          });

          return updatedUser;
        } catch (error: any) {
          const errorMessage = error?.response?.data?.message || error?.message || 'Failed to update user';
          set({
            error: errorMessage,
            isLoadingUser: false,
          });
          throw error;
        }
      },

      /**
       * EN: Delete user by ID
       * VI: Xóa user theo ID
       */
      deleteUser: async (id: string) => {
        set({ isLoadingUser: true, error: null });

        try {
          await deleteUser(id);

          // Remove from users list
          const { users } = get();
          const filteredUsers = users.filter(user => user.id !== id);

          set({
            users: filteredUsers,
            currentUser: null,
            isLoadingUser: false,
          });
        } catch (error: any) {
          const errorMessage = error?.response?.data?.message || error?.message || 'Failed to delete user';
          set({
            error: errorMessage,
            isLoadingUser: false,
          });
          throw error;
        }
      },

      /**
       * EN: Bulk delete multiple users
       * VI: Xóa nhiều users cùng lúc
       */
      bulkDeleteUsers: async (ids: string[]) => {
        set({ isLoading: true, error: null });

        try {
          await bulkDeleteUsers(ids);

          // Remove from users list
          const { users } = get();
          const filteredUsers = users.filter(user => !ids.includes(user.id));

          set({
            users: filteredUsers,
            isLoading: false,
          });
        } catch (error: any) {
          const errorMessage = error?.response?.data?.message || error?.message || 'Failed to bulk delete users';
          set({
            error: errorMessage,
            isLoading: false,
          });
          throw error;
        }
      },

      /**
       * EN: Bulk update user roles
       * VI: Cập nhật vai trò cho nhiều users
       */
      bulkUpdateUserRoles: async (updates: Array<{ id: string; role: Role }>) => {
        set({ isLoading: true, error: null });

        try {
          await bulkUpdateUserRoles(updates);

          // Update in users list
          const { users } = get();
          const updatedUsers = users.map(user => {
            const update = updates.find(u => u.id === user.id);
            return update ? { ...user, role: update.role } : user;
          });

          set({
            users: updatedUsers,
            isLoading: false,
          });
        } catch (error: any) {
          const errorMessage = error?.response?.data?.message || error?.message || 'Failed to bulk update user roles';
          set({
            error: errorMessage,
            isLoading: false,
          });
          throw error;
        }
      },

      /**
       * EN: Clear current user data
       * VI: Xóa dữ liệu current user
       */
      clearCurrentUser: () => {
        set({ currentUser: null });
      },

      /**
       * EN: Clear error state
       * VI: Xóa trạng thái lỗi
       */
      clearError: () => {
        set({ error: null });
      },

      /**
       * EN: Reset store to initial state
       * VI: Reset store về trạng thái ban đầu
       */
      reset: () => {
        set(initialState);
      },
    }),
    {
      name: 'users-store', // DevTools store name
    }
  )
);