import { create } from 'zustand';
import { query, queryLogin } from '@/modules';
import { message } from '@/modules/message';
type UserStore = {
  showEdit: boolean;
  setShowEdit: (showEdit: boolean) => void;
  showNameEdit: boolean;
  setShowNameEdit: (showNameEdit: boolean) => void;
  showCheckUserExist: boolean;
  setShowCheckUserExist: (showCheckUserExist: boolean) => void;
  formData: any;
  setFormData: (formData: any) => void;
  loading: boolean;
  setLoading: (loading: boolean) => void;
  list: any[];
  getList: () => Promise<void>;
  updateData: (data: any) => Promise<void>;
  updateSelf: (data: any) => Promise<any>;
  deleteData: (id: string) => Promise<void>;
  showChangePassword: boolean;
  setShowChangePassword: (showChangePassword: boolean) => void;
};
export const useUserStore = create<UserStore>((set, get) => {
  return {
    showEdit: false,
    setShowEdit: (showEdit) => set({ showEdit }),
    showNameEdit: false,
    setShowNameEdit: (showNameEdit) => set({ showNameEdit }),
    showCheckUserExist: false,
    setShowCheckUserExist: (showCheckUserExist) => set({ showCheckUserExist }),
    formData: {},
    setFormData: (formData) => set({ formData }),
    loading: false,
    setLoading: (loading) => set({ loading }),
    list: [],
    getList: async () => {
      set({ loading: true });

      const res = await query.post({
        path: 'user',
        key: 'list',
      });
      set({ loading: false });
      if (res.code === 200) {
        set({ list: res.data });
      } else {
        message.error(res.message || 'Request failed');
      }
    },
    updateData: async (data) => {
      const { getList } = get();
      const res = await query.post({
        path: 'user',
        key: 'update',
        data,
      });
      if (res.code === 200) {
        message.success('Success');
        set({ showEdit: false, formData: [] });
        getList();
      } else {
        message.error(res.message || 'Request failed');
      }
    },
    updateSelf: async (data) => {
      const res = await query.post({
        path: 'user',
        key: 'updateSelf',
        data,
      });
      if (res.code === 200) {
        message.success('Success');
        set({ formData: res.data });
        return res.data;
      } else {
        message.error(res.message || 'Request failed');
      }
    },
    deleteData: async (id) => {
      const { getList } = get();
      const res = await query.post({
        path: 'user',
        key: 'delete',
        id,
      });
      if (res.code === 200) {
        getList();
        message.success('Success');
      } else {
        message.error(res.message || 'Request failed');
      }
    },
    showChangePassword: false,
    setShowChangePassword: (showChangePassword) => set({ showChangePassword }),
  };
});
