'use client';
import Backgroundimage from '@/components/Backgroundimage';
import Button from '@/components/Button';
import Input from '@/components/Input';
import Link from 'next/link';
import Label from '@/components/Label';
import Logo from '@/components/Logo';
import { useRouter } from 'next/router';
import { toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import { signOut, useSession } from 'next-auth/react';
import React, { useEffect, useState } from 'react';
import validateLoginSchema from '../validations/loginFormValidationSchema';
import useLoginMutation from '../hooks/useLoginMutation';
import { useContext } from 'react';
import { MyContext } from '@/components/MyContext';
import { setCookie } from 'cookies-next';
import { data } from 'autoprefixer';

type LoginFormValues = {
  email: any;
  password: string;
};

const LoginForm = () => {
  const { data: session, status } = useSession();
  const [IsLogged, setIsLogged] = useState(false);
  const user = session?.user;
  const router = useRouter();
  // accessing a context api
  const { myState, setMyState, setUserInfo, userInfo } = useContext(MyContext);
  if (session) {
    router.push('/presenter_rota');
  }

  // Deepak sir code
  // TODO Hotfix for logout Not happen when supporter click on logout
  const clearIt = async () => {
    // Logout
    await signOut();
  };

  // TODO Hotfix for logout Not happen when supporter click on logout
  useEffect(() => {
    if (session === null && status === 'unauthenticated') {
      clearIt();
    }
  }, []);

  useEffect(() => {
    if (session != null && status === 'authenticated') {
      // redirect back to Dashboard
      router.push('/presenter_rota');
    }
  }, [router, session, status]);

  // Toast success message
  const handleSuccessToastMessage = () => {
    toast.success('Login Successfully !', {
      position: toast.POSITION.TOP_CENTER,
    });
  };

  // Toast failed message
  const handleErrorToastMessage = () => {
    toast.error('Enter valid Username and Password!', {
      position: toast.POSITION.TOP_CENTER,
    });
  };

  // updating string value
  const handleStateChange = (username: string) => {
    setMyState(username);
  };

  // updating context api
  const handleUserInfo = (
    username: string,
    email: string,
    password: string
  ) => {
    setUserInfo({
      username: username,
      email: email,
      password: password,
    });
  };

  const {
    register,
    handleSubmit,
    getValues,
    formState: { errors },
  } = useForm<LoginFormValues>({
    mode: 'onChange',
    resolver: yupResolver(validateLoginSchema),
  });

  const loginMutation = useLoginMutation();

  const resetErrorMsg = () => {
    loginMutation.reset();
  };

  const storeDataInContext = async (email: string) => {
    // here perforning post request for storing user data
    const res = await fetch('api/login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email: email }),
    });
    let loginResponse = await res.json();
    if (res.ok) {
      localStorage.setItem('isAdminUser', loginResponse.roles);
      handleUserInfo(
        loginResponse?.username,
        loginResponse?.email,
        loginResponse?.password
      );
      handleStateChange(loginResponse?.username);
    }
  };

  const onSubmit = async (data: LoginFormValues) => {
    loginMutation.mutate(data, {
      onSuccess(data, variables, context) {
        storeDataInContext(variables.email);
        handleSuccessToastMessage();
        // setCookie("logged", "true"); // DO NOT USE COOKIE REMOVE ASAP
        resetErrorMsg();
      },
      onError(error, variables, context) {
        handleErrorToastMessage();
        resetErrorMsg();
      },
    });
  };

  let errorMessage = '';
  if (
    !loginMutation.isLoading &&
    loginMutation.isError &&
    loginMutation.error instanceof Error
  ) {
    errorMessage = loginMutation.error.message;
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div className="flex">
        {/* Image Section start */}
        <Backgroundimage />
        {/* Image Section end */}
        <div className="w-1/2 m-auto pl-[103px]">
          <Logo divclassname="mb-[35px]" width="189" height="55" />
          <Label
            labelname="Welcome back!"
            divclassname="mb-[60px]"
            labelclassname="text-purple text-[32px] font-semibold"
          />
          <div className="relative mt-6">
            <Input
              placeholder="Email"
              type="email"
              className="w-[60%] h-[60px] border p-[10px] border-solid border-black rounded-[5px]"
              // label="Email"
              // autoComplete="off"
              // error={errors.email?.message}
              {...register('email')}
              // required
            />
          </div>

          <div className="relative mt-6">
            <Input
              placeholder="Password"
              type="password"
              // /* className="w-[60%]" */
              // label="Password"
              // autoComplete="off"
              // error={errors.password?.message}
              {...register('password')}
              className="w-[60%] border h-[60px] p-[10px] border-solid border-black rounded-[5px]"
              // required
              // inputclassname="w-full"
            />
          </div>

          {loginMutation.isError && errorMessage ? (
            <p className="form-error">
              Please add valid username and password!
            </p>
          ) : null}

          <div className="flex custom-flex">
            <div>
              <button
                className="text-white bg-purple rounded-[5px] p-2 mr-6 px-8 py-2 text-lg"
                type="submit"
                disabled={loginMutation.isLoading}
              >
                Login
              </button>
              {/* <Button
                    linktext="Register"
                    linkclassname="text-white bg-purple rounded-[5px]"
                    link="/"
                  /> */}
            </div>
            <div>
              <Link href="/register">
                <button
                  className="text-white bg-purple rounded-[5px] p-2 mr-6 px-6 py-2 text-lg"
                  type="submit"
                >
                  Registration
                </button>
              </Link>
            </div>
          </div>
        </div>
      </div>
    </form>
  );
};

export default LoginForm;
