import { baseAPI } from "@/Shared/API/baseAPI";
import { IFetch } from "@/Shared/types";
import axios from "axios";
import { create } from "zustand";

interface SignInStore extends IFetch {
  login: (email: string, password: string) => Promise<void>;
  cleanRedirect: () => void;
  emailError: string;
  passwordError: string;
  redirect: boolean;
}

export const useSignIn = create<SignInStore>((set) => ({
  loading: false,
  error: "",
  emailError: "",
  passwordError: "",
  redirect: false,
  login: async (email: string, password: string) => {
    if (!email.trim()) {
      set({ emailError: "Пожалуйста введите почту" });
      set({ passwordError: "" });

      return;
    }
    if (!password.trim()) {
      set({ passwordError: "Пожалуйста введите пароль" });
      set({ emailError: "" });
      return;
    }

    const user = {
      email,
      password,
    };

    try {
      set({ loading: true });

      const response = await axios.post(
        `${baseAPI}/users/login/`,
        user
      );

      localStorage.setItem("tokens", JSON.stringify(response.data));

      set({ emailError: "" });
      set({ passwordError: "" });
      set({ error: "" });
      set({ redirect: true });
    } catch (error: any) {
      set({ emailError: "" });
      set({ passwordError: "" });
      set({ error: error.message });
    } finally {
      set({ loading: false });
    }
  },
  cleanRedirect: () => {
    set({ redirect: false });
  },
}));
