import { motion } from "framer-motion";
import img from "../assets/images/auth-bg.png";
import logo from "../assets/images/logo.png";
import Textfield from "../components/Textfeild/Textfeild";
import Button from "../components/Button/Button";
import Typography from "../components/Typography/Typography";
import {
  useUserProfileStore,
  useUserStore,
} from "../context/zustand-store/userStore";
import { getBase64ImageSrc } from "../utils/getBase64ImageSrc";
import { useApiMutation } from "../utils/useApiRequest";
import { useEffect, useState } from "react";
import noImage from "../assets/images/not-loaded-captcha.png";
import { ArrowPathIcon } from "@heroicons/react/24/outline";

import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { zValidate, zValidateString } from "../data/getFormTypeErrors";
import { useToast } from "../hooks/useToast";

const containerVariants = {
  hidden: {},
  show: {
    transition: {
      staggerChildren: 0.1,
    },
  },
};

const fadeInUp = {
  hidden: { opacity: 0, y: 10 },
  show: { opacity: 1, y: 0, transition: { duration: 0.4, ease: "easeOut" } },
};

const schema = z.object({
  nationalId: zValidateString("کد ملی"),
  password: zValidateString("کلمه عبور"),
  captcha: z.coerce
    .string(zValidate("کپچا"))
    .min(1, "کپچا الزامی است")
    .min(1, "فیلد نمیتواند خالی باشد!"),
});

type FormValues = z.infer<typeof schema>;

interface Captcha {
  captcha_image: string | null;
  captcha_key: string | null;
}

export const Auth = () => {
  const { setUser } = useUserStore();
  const { setUserProfile } = useUserProfileStore();

  const mutationCaptcha = useApiMutation({
    api: "/captcha/",
    method: "post",
    disableBackdrop: true,
  });

  const mutationLogin = useApiMutation({
    api: "/auth/api/v1/login/",
    method: "post",
    disableBackdrop: false,
  });

  const mutationProfile = useApiMutation({
    api: "/auth/api/v1/user/profile/",
    method: "get",
    disableBackdrop: false,
  });

  const handleGetCaptcha = async () => {
    const data = await mutationCaptcha.mutateAsync({});
    setCaptcha(data);
  };
  const showToast = useToast();

  const [captcha, setCaptcha] = useState<Captcha>();

  const {
    register,
    handleSubmit,
    formState: { errors },
    setValue,
    watch,
  } = useForm<FormValues>({
    resolver: zodResolver(schema),
  });

  useEffect(() => {
    handleGetCaptcha();
  }, []);

  const getProfile = async () => {
    const profile = await mutationProfile.mutateAsync({});
    if (typeof profile === "object") {
      setUserProfile(profile);
    }
  };

  const onSubmit = async (data: FormValues) => {
    try {
      const response = await mutationLogin.mutateAsync({
        username: data.nationalId,
        password: data.password,
        captcha_code: data.captcha.toString(),
        captcha_key: `rest_captcha_${captcha?.captcha_key ?? ""}.0`,
      });

      setUser({ auth: response?.access });
      getProfile();
    } catch (error: any) {
      handleGetCaptcha();
      if (error?.status === 403) {
        setValue("captcha", "");
        showToast("کپچا اشتباه است!", "error");
      } else {
        setValue("captcha", "");
        showToast("نام کاربری یا رمز عبور اشتباه است!", "error");
      }
    }
  };

  const imageSrc = getBase64ImageSrc(captcha?.captcha_image ?? "");

  return (
    <div
      className="relative flex h-screen flex-col md:flex-row overflow-y-auto dark:bg-dark-900"
      style={{
        backgroundImage: `url(${img})`,
        backgroundSize: "cover",
        backgroundPosition: "center",
      }}
    >
      <div className="absolute inset-0 bg-black opacity-0 dark:opacity-50 transition-opacity duration-300 pointer-events-none z-0" />
      <motion.div
        initial={{ scale: 0.95, opacity: 0 }}
        animate={{ scale: 1, opacity: 1 }}
        transition={{ duration: 0.2 }}
        className="flex w-full h-screen items-center justify-center px-6 sm:px-12 md:px-24 lg:px-40 py-8"
      >
        <motion.form
          onSubmit={handleSubmit(onSubmit)}
          variants={containerVariants}
          initial="hidden"
          animate="show"
          className="w-full p-10 bg-white rounded-xl flex flex-col max-w-sm space-y-2 items-center justify-center dark:bg-dark-800"
        >
          <motion.img
            variants={fadeInUp}
            src={logo}
            alt="Logo"
            className="mx-auto w-20 select-none mb-4 dark:brightness-100 dark:opacity-100"
          />
          <motion.div variants={fadeInUp}>
            <Typography className="mb-4 select-none">سامانه رصدام</Typography>
          </motion.div>

          <motion.div variants={fadeInUp} className="w-full">
            <Textfield
              fullWidth
              placeholder="نام کاربری"
              {...register("nationalId")}
              error={!!errors.nationalId}
              helperText={errors.nationalId?.message}
            />
          </motion.div>
          <motion.div variants={fadeInUp} className="w-full">
            <Textfield
              fullWidth
              placeholder="کلمه عبور"
              password
              {...register("password")}
              error={!!errors.password}
              helperText={errors.password?.message}
            />
          </motion.div>

          <motion.div variants={fadeInUp} className="flex w-full items-center">
            <Textfield
              fullWidth
              className="w-[100%]"
              placeholder="کد امنیتی"
              isNumber
              {...register("captcha")}
              value={watch("captcha") || ""}
              error={!!errors.captcha}
              helperText={errors.captcha?.message}
            />
            <button
              type="button"
              onClick={handleGetCaptcha}
              className="p-1 rounded-full hover:bg-gray-200 transition"
            >
              <ArrowPathIcon className="h-5 w-5 text-gray-600" />
            </button>
            <div className="h-10 w-[180px] overflow-hidden rounded-2xl">
              <img
                className="w-full h-full object-cover scale-100"
                src={imageSrc.endsWith(",") ? noImage : imageSrc}
                alt="captcha"
              />
            </div>
          </motion.div>

          <motion.div variants={fadeInUp} className="w-full">
            <Button fullWidth className="mt-1" type="submit">
              ورود
            </Button>
          </motion.div>
        </motion.form>
      </motion.div>
    </div>
  );
};
