import { useState, useEffect } from "react";
import { Button, CustomSpinner, FloatLabelInput } from "..";
import CustomModal from "../modal/CustomModal";
import { useNavigate, useLocation } from "react-router-dom";
import { RouteHandler } from "../../router/routes";
import { RequestStatus } from "../../core/models";
import { employerLogin } from "../../core/apiRequest";


type FormType = {
  email: string;
  password: string;
};

type HandleChange = {
  name: string;
  value: string;
};

export default function Login() {

  const navigate = useNavigate()
  const {state} = useLocation()

  const [modal, setModal] = useState<boolean>(false)
  const [expiredLinkModal, setExpiredLinkModal] = useState<boolean>(false)

  const [requestStatus, setRequestStatus] = useState<RequestStatus>({loading:false, status:null, message:'', data:{}})

  let [formDetails, setFormDetails] = useState<FormType>({
    email: "",
    password: "",
  });

  const handleFormChange = ({
    target: { name, value },
  }: {
    target: HandleChange;
  }): any => {
    setFormDetails((prev:FormType) => ({ ...prev, [name]: value }));
  };

  const loginFxn = () => {
    let reqData = {
      application_uid: state?.application_uid,
      password: formDetails?.password,
      username: formDetails.email
    }

    setRequestStatus((prev:RequestStatus) => ({...prev, loading:true}))
    employerLogin(reqData).then(res => {
      // console.log('RES', res)
      if(!res?.data?.call_return){
        setRequestStatus({loading:false, status:false, message:'Email/Password is wrong', data:{}})
        return setTimeout(()=>{
          setRequestStatus({loading:false, status:null, message:'', data:{}})
        },4000)
      }
      setRequestStatus({loading:false, status:true, message:'login successful', data:res?.data})
      setModal(true)
    }).catch(err =>{
      setRequestStatus({loading:false, status:false, message:'something went wrong', data:{}})
      console.log(err)
      return setTimeout(()=>{
        setRequestStatus({loading:false, status:null, message:'', data:{}})
      },4000)
    })
  }

  useEffect(()=>{
    if(!state?.application_uid){
      setExpiredLinkModal(true)
    }
  },[])

  return (
    <>
      <div className={`w-full overflow-y-auto bg-top bg-cover`}>
        <div className="w-full flex justify-center">
          <div className="w-full md:max-w-[570px]">
            <div className="bg-white w-full rounded-2xl border-2 border-black">
              <div className="w-full p-5 sm:p-10 lg:p-20 flex flex-col justify-between items-center h-full">
                {expiredLinkModal && 
                  <p className="text-xl mb-4 text-center font-medium text-red-500 dark:text-black">
                    Invalid Link, Please proceed to your email and click on the link to continue
                  </p>
                }
                <div className={`${expiredLinkModal && 'hidden'} w-full`}>
                  <div className="mb-4">
                    <h1 className="text-2xl text-center font-bold leading-3 tracking-wide text-black dark:text-black">
                      Welcome!
                    </h1>
                    <p className="text-xl mt-4 text-center font-medium text-black dark:text-black">
                      Please login with your email and default password provided to you
                    </p>
                  </div>

                  <div className="w-full">
                    {/* INPUTS */}
                    <div className="w-full">
                      <div className="relative my-2 py-2">
                        <FloatLabelInput
                          id="email"
                          name="email"
                          type="email"
                          placeHolder="Email"
                          labelName="Email"
                          value={formDetails.email}
                          inputClass=""
                          onChange={handleFormChange}
                        />
                      </div>
                      <div className="relative my-2 py-2">
                        <FloatLabelInput
                          id="password"
                          name="password"
                          type="password"
                          placeHolder="Password"
                          labelName="Password"
                          value={formDetails.password}
                          inputClass=""
                          onChange={handleFormChange}
                        />
                      </div>
                    </div>

                    <div className="mt-10 w-full flex items-center gap-2">
                      <Button
                        text="Enter"
                        className="rounded-md w-full sm:w-2/5 text-xl capitalize font-bold"
                        onClick={loginFxn}
                        disabled={!formDetails.password || !formDetails.email || requestStatus.loading}
                      />
                      {requestStatus.loading &&
                        <CustomSpinner />
                      }
                      {/* <Link to='' className='text-black text-sm'>Forget your password?</Link> */}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      { modal &&
        <CustomModal>
          <div className="py-5 bg-white w-[90%] max-w-[420px] flex flex-col justify-center items-center rounded-xl">
            <p className="px-10 md:px-20 text-sm font-bold text-slate-700 text-center tracking-wide leading-normal">We have sent you a verification code to complete this Login. Please check your phone number</p>
            <div className="px-5 md:px-10 w-full flex justify-end">
              <button
                className="font-bold text-[11px] lg:text-[13px] text-[#5A2C82]"
                onClick={()=>{navigate(RouteHandler.otppage, { state: {verify_uid: requestStatus?.data?.verify_uid, application_uid: requestStatus?.data?.records?.application_uid }, replace:true })}}
              >
                Ok
              </button>
            </div>
          </div>
        </CustomModal>
      }
    </>
  );
}
