import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { sendRpcRequest } from "../../services/apiClient";
import { TG_USER_ID } from "../../constants/constants";
import type { ISession } from "../../types/account.types";

interface IAccountState {
  session: ISession;
  loading: boolean;
  isCheckPasswordLoading: boolean;
  deletingData: boolean;
  errorCheckPassword: string | null;
}

const initialState: IAccountState = {
  session: {
    login: "",
    emailVerified: false,
    subDateEnd: "",
    paid: true,
    timeZoneStr: "",
  },
  loading: false,
  isCheckPasswordLoading: false,
  deletingData: false,
  errorCheckPassword: null,
};

export const accountSession = createAsyncThunk(
  "account/session",
  async (_, { rejectWithValue }) => {
    try {
      const response = await sendRpcRequest<ISession>("account.session");

      return response;
    } catch (error: unknown) {
      if (typeof error === "object" && error !== null && "message" in error) {
        return rejectWithValue(error.message);
      }

      return rejectWithValue("Unknown error occurred");
    }
  }
);

export const checkPassword = createAsyncThunk(
  "account/checkPassword",
  async (password: string, { rejectWithValue }) => {
    try {
      const response = await sendRpcRequest<{
        message: string;
        success: boolean;
      }>("account.checkpwd", {
        password,
      });

      if (response?.message === "valid") {
        const deleteAccountResponse = await sendRpcRequest<{
          message: string;
          success: boolean;
        }>("account.deleteaccount");

        if (deleteAccountResponse.success) {
          localStorage.removeItem(`token-${TG_USER_ID}`);
          localStorage.removeItem(`pincode-${TG_USER_ID}`);
          sessionStorage.removeItem(`pincode-${TG_USER_ID}`);
          window.location.href = "/";
        }

        return response;
      }

      return response;
    } catch (error: unknown) {
      if (typeof error === "object" && error !== null && "message" in error) {
        return rejectWithValue(error.message);
      }
      return rejectWithValue("Unknown error occurred");
    }
  }
);

export const setTimezone = createAsyncThunk(
  "account/setTimezone",
  async (
    { zone, offset }: { zone: string; offset: number },
    { rejectWithValue }
  ) => {
    try {
      const response = await sendRpcRequest("account.setTimeZone", {
        zone,
        offset,
      });

      return response;
    } catch (error) {
      if (typeof error === "object" && error !== null && "message" in error) {
        return rejectWithValue((error as { message: string }).message);
      }
      return rejectWithValue("Unknown error occurred");
    }
  }
);

export const deleteAudio = createAsyncThunk(
  "account/deleteAudio",
  async (_, { rejectWithValue }) => {
    try {
      const response = await sendRpcRequest("account.deleteAudio");

      return response;
    } catch (error) {
      if (typeof error === "object" && error !== null && "message" in error) {
        return rejectWithValue((error as { message: string }).message);
      }
      return rejectWithValue("Unknown error occurred");
    }
  }
);

export const deleteImage = createAsyncThunk(
  "account/deleteImage",
  async (_, { rejectWithValue }) => {
    try {
      const response = await sendRpcRequest("account.deleteImage");

      return response;
    } catch (error) {
      if (typeof error === "object" && error !== null && "message" in error) {
        return rejectWithValue((error as { message: string }).message);
      }
      return rejectWithValue("Unknown error occurred");
    }
  }
);

export const deleteMedia = createAsyncThunk(
  "account/deleteMedia",
  async (_, { rejectWithValue }) => {
    try {
      const response = await sendRpcRequest("account.deleteMedia");

      return response;
    } catch (error) {
      if (typeof error === "object" && error !== null && "message" in error) {
        return rejectWithValue((error as { message: string }).message);
      }
      return rejectWithValue("Unknown error occurred");
    }
  }
);

const accountSlice = createSlice({
  name: "account",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(accountSession.pending, (state) => {
        state.loading = true;
      })
      .addCase(accountSession.fulfilled, (state, action) => {
        state.loading = false;
        state.session = action.payload;
      })
      .addCase(accountSession.rejected, (state) => {
        state.loading = false;
      })

      .addCase(checkPassword.pending, (state) => {
        state.isCheckPasswordLoading = true;
      })
      .addCase(checkPassword.fulfilled, (state) => {
        state.isCheckPasswordLoading = false;
        state.errorCheckPassword = null;
      })
      .addCase(checkPassword.rejected, (state, action) => {
        state.isCheckPasswordLoading = false;
        state.errorCheckPassword = action.payload as string;
      })

      .addCase(setTimezone.pending, (state) => {
        state.loading = true;
      })
      .addCase(setTimezone.fulfilled, (state) => {
        state.loading = false;
      })
      .addCase(setTimezone.rejected, (state) => {
        state.loading = false;
      })

      .addCase(deleteAudio.pending, (state) => {
        state.deletingData = true;
      })
      .addCase(deleteAudio.fulfilled, (state) => {
        state.deletingData = false;
      })
      .addCase(deleteAudio.rejected, (state) => {
        state.deletingData = false;
      })

      .addCase(deleteImage.pending, (state) => {
        state.deletingData = true;
      })
      .addCase(deleteImage.fulfilled, (state) => {
        state.deletingData = false;
      })
      .addCase(deleteImage.rejected, (state) => {
        state.deletingData = false;
      });
  },
});

export default accountSlice.reducer;
