import Image from "next/image";
import mail from "./icons/mail.svg";
import AuthInput from "@/features/AuthInput/AuthInput";
import "./send-email.scss";
import { useState } from "react";
import { apiInstance } from "@/shared/config/apiConfig";
import Loader from "@/shared/ui/components/Loader/Loader";
import { AxiosError } from "axios";

interface ISendEmailProps {
  setChangeForm: (boolean: boolean) => void;
}

const SendEmail: React.FC<ISendEmailProps> = ({
  setChangeForm,
}: ISendEmailProps) => {
  const [error, setError] = useState<string>("");
  const [loader, setLoader] = useState<boolean>(false);

  const handleSubmit: React.MouseEventHandler<
    HTMLFormElement
  > = async (e) => {
    e.preventDefault();
    const formData = new FormData(e.currentTarget);

    if (!formData.get("email")) {
      return setError("Заполните поле");
    }

    try {
      setError("");
      setLoader(true);
      const res = await apiInstance.post(
        "/users/password_reset/",
        formData
      );

      if ([200, 201].includes(res.status)) {
        console.log(res.data);
        setChangeForm(true);
      }
    } catch (error: unknown) {
      if (error instanceof AxiosError) {
        console.log(error);
        if (error.response?.status === 400) {
          setError("Пользователь с таким email не найден");
        } else {
          setError("Ошибка на стороне сервера");
        }
      } else {
        setError("Произошла непредвиденная ошибка");
      }
    } finally {
      setLoader(false);
    }
  };
  return (
    <div className="auth-wrapper">
      <div className="auth-icon2">
        <Image src={mail} alt="Key Icon" />
      </div>
      <div className="auth-header">
        <h2>Введите email</h2>
        <p>
          Введите email и мы отправим код для восстановления пароля
        </p>
      </div>

      <form onSubmit={handleSubmit} className="send-email">
        <AuthInput
          type="email"
          name="email"
          label="Email"
          error={error}
          placeholder="Введите email"
        />
        <button type="submit">
          {loader ? <Loader /> : "Отправить код"}
        </button>
      </form>
      <button
        onClick={() => setChangeForm(true)}
        className="send-email-confirm-code"
      >
        Потвердить код
      </button>
    </div>
  );
};

export default SendEmail;
