import React, { useState } from "react";
import Modalbutton from "./Modalbutton";
import ModalInput from "./ModalInput";
// import { toast } from 'react-toastify';
import Image from "next/image";
import toast, { Toaster } from "react-hot-toast";
import { useForm } from "react-hook-form";
import "react-toastify/dist/ReactToastify.css";
// import { useFormik } from 'formik';
// import signUpSchema from "@/components/schemas/signupschema";
import presenterschema from "@/components/schemas/presenterschema";
import { useQueryClient } from "react-query";

import { useRouter } from "next/router";
// import { useMutation } from "react-query";
import { useMutation } from "react-query";
import axios from "axios";

// type for interface
interface Item {
  // userid: number;
  name: string;
  initials: string;
  surname: string;
  email: string;
  phone: string;
  profilePhoto: FileList;
  presenterpassword: string;
}

const Modal = ({ payload, isVisible, onRequestClose, modaltitle }: any) => {
  // file(Image) for uploading in our locally
  const [selectedFile, setSelectedFile] = useState<File>();
  const [imageSelect, setImageSelect] = useState<boolean>(true);
  // Access the client and validating
  const [files, setFiles] = useState("");
  const queryClient = useQueryClient();

  // function which handling image add in public/images
  const handleUpload = async () => {
    // try {
    //   if (!selectedFile) return;
    // const { data } = await axios.post('/api/uploadavatar', formData);
    //
    // } catch (error: any) {
    //
    // }
  };



   //refetching data for update
   const handleRefetch = () => {
    queryClient.invalidateQueries('presenterData');
  };
  // get functions to build form with useForm() hook
  const { register, handleSubmit, reset, setValue, formState } = useForm({
    defaultValues: {
      name: payload?.firstname,
      email: payload?.email,
      initials: payload?.initials,
      surname: payload?.surname,
      phone: payload?.phone,
      profileImage: payload?.profileImage,
      presenterpassword: "",
      // presenterpassword:payload?.presenterpassword,
    },
  });
  const { errors } = formState;

  // toast message
  const showToastMessage = () => {
    // toast.success('Successfully Added!');
  };
  const pathName = useRouter().pathname;
  if (!isVisible) return null;
  const handleClose = (e: any) => {
    if (e.target.className === "") onRequestClose();
  };

  // onSubmit function
  const onSubmit = async (values: any) => {
   
    if (pathName === "/presenter_rota") {
      const formData = new FormData();
      formData.append("myImage", selectedFile as File);
      formData.append("name", values.name);
      formData.append("initials", values.initials);
      formData.append("surname", values.surname);
      formData.append("phone", values.phone);
      formData.append("email", values.email);
      formData.append("presenterpassword", values.presenterpassword);
      // formData.append('email', values.email);
      onRequestClose();
      const res = await axios.post("/api/uploadavatar", formData);
     
      if (res.status === 200) {
        toast.success("Successfully Added!");
        reset();
      }
    }

    if (pathName === "/presenters") {
      const formData = new FormData();
      formData.append("myImage", selectedFile as File);
      formData.append("name", values.name);
      formData.append("initials", values.initials);
      formData.append("surname", values.surname);
      formData.append("phone", values.phone);
      formData.append("email", values.email);
      formData.append("presenterpassword", values.presenterpassword);
      formData.append("presenterUserId", payload.userid);
      // formData.append('email', values.email);
      // onRequestClose();
      // const res = await axios.post('/api/uploadavatar', formData);
      // const res = await fetch('/api/uploadavatar', {
      //   method: 'POST',
      //   body: formData,
      //   headers: { 'Content-Type': 'application/json' },
      // });
      onRequestClose();
      const res = await fetch("/api/uploadavatar", {
        method: "POST",
        body: formData,
      });
      console.log("result",res)
      
      
      if (res.ok) {
        toast.success("Successfully updated!!");
        handleRefetch();
        reset();
      } else {
        toast.success("Successfully failed!!");
        // onRequestClose();
      }
      
    }
  };

  return (
    <>
      <form onSubmit={handleSubmit(onSubmit)}>
        <div
          className="fixed inset-0 z-50 flex items-center justify-center overflow-x-hidden overflow-y-auto outline-none focus:outline-none"
          // onClick={}
        >
          <div className="relative w-auto mx-auto my-6 max-w-7xl">
            {/*content*/}
            <div className="relative flex flex-col w-full bg-white border-0 rounded-lg shadow-lg outline-none focus:outline-none">
              {/*header*/}
              <div className="grid items-start grid-cols-[98%_2%] w-full gap-3 p-5 border-b border-solid rounded-t bg-purple border-slate-200">
                <h3 className="text-3xl font-semibold text-center text-white">
                  {modaltitle}
                </h3>
                <Modalbutton
                  onRequestClose={onRequestClose}
                  buttonclassname="float-root p-1 text-3xl font-semibold leading-none text-black bg-transparent border-0 outline-none opacity-100 focus:outline-none z-[1]"
                  spanclassname="block w-6 h-6 text-2xl text-white bg-transparent outline-none opacity-100 focus:outline-none float-right"
                  buttontext="x"
                />
              </div>
              {/*body*/}
              {pathName === "/presenter_rota" || pathName === "/presenters" ? (
                <div className="relative p-6 grid grid-cols-2 gap-3 mb-[38px] mt-[45px]">
                  <div className="">
                    <div className="mb-[38px]">
                      <ModalInput
                        inputplaceholder="Name"
                        inputtype="text"
                        handleForm={{ ...register("name", { required: true }) }}
                        handleId="name"
                        handleAutoComplete="off"
                        inputclassname="w-full"
                        labelclassname="left-[3%]"
                      />
                      {errors.name && (
                        <p className="text-red-700 error">
                          First Name is required.
                        </p>
                      )}
                    </div>
                    <div className="mb-[38px]">
                      <ModalInput
                        inputplaceholder="Email"
                        inputtype="email"
                        handleForm={{
                          ...register("email", { required: true }),
                        }}
                        handleId="email"
                        handleAutoComplete="off"
                        inputclassname="w-full"
                        labelclassname="left-[3%]"
                      />
                      {errors.email && (
                        <p className="text-red-700 error">
                          Enter a Valid Email.
                        </p>
                      )}
                    </div>
                    {pathName === "/presenters" ? (
                      <div className="mb-[38px]">
                        <ModalInput
                          inputplaceholder="password"
                          inputtype="password"
                          handleForm={{
                            ...register("presenterpassword", {
                              required: false,
                            }),
                          }}
                          handleId="presenterpassword"
                          handleAutoComplete="off"
                          inputclassname="w-full"
                          labelclassname="left-[3%]"
                        />
                        {errors.presenterpassword && (
                          <p className="text-red-700 error">
                            Enter a Valid password.
                          </p>
                        )}
                      </div>
                    ) : (
                      <div className="mb-[38px]">
                        <ModalInput
                          inputplaceholder="password"
                          inputtype="password"
                          handleForm={{
                            ...register("presenterpassword", {
                              required: true,
                            }),
                          }}
                          handleId="presenterpassword"
                          handleAutoComplete="off"
                          inputclassname="w-full"
                          labelclassname="left-[3%]"
                        />
                        {errors.presenterpassword && (
                          <p className="text-red-700 error">
                            Enter a Valid password.
                          </p>
                        )}
                      </div>
                    )}
                  </div>
                  <div className="">
                    <div className="mb-[38px] flex">
                      <div>
                        <ModalInput
                          inputplaceholder="Intials"
                          inputtype="text"
                          handleForm={{
                            ...register("initials", { required: true }),
                          }}
                          handleId="initials"
                          handleAutoComplete="off"
                          inputclassname="w-[95%]"
                          labelclassname="left-[51%]"
                        />
                        {errors.initials && (
                          <p className="text-red-700 error">
                            Enter a valid Intials.
                          </p>
                        )}
                      </div>
                      <div>
                        <ModalInput
                          inputplaceholder="Surname"
                          inputtype="text"
                          handleForm={{
                            ...register("surname", { required: true }),
                          }}
                          handleId="surname"
                          handleAutoComplete="off"
                          inputclassname="w-full"
                          labelclassname="left-[75%]"
                        />
                        {errors.surname && (
                          <p className="text-red-700 error">Enter a surname.</p>
                        )}
                      </div>
                    </div>
                    <div>
                      <ModalInput
                        inputplaceholder="Phone"
                        inputtype="number"
                        handleForm={{
                          ...register("phone", { required: true }),
                        }}
                        handleId="phone"
                        handleAutoComplete="off"
                        inputclassname="w-full"
                        labelclassname="left-[51%]"
                      />
                      {errors.phone && (
                        <p className="text-red-700 error">
                          Enter a valid number.
                        </p>
                      )}
                    </div>

                    {pathName === "/presenter_rota" ? (
                      <div className="mt-[50px]">
                        <input
                          type="file"
                          id="profileImage"
                          {...register("profileImage", { required: true })}
                          onChange={({ target }) => {
                            if (target.files) {
                              const file = target.files[0];

                              setSelectedFile(file);
                              setImageSelect(false);
                            }
                          }}
                        />
                        {errors.profileImage && imageSelect && (
                          <p className="text-red-700 error">
                            Enter a profile image.
                          </p>
                        )}
                      </div>
                    ) : (
                      // this part help in update image
                      <div className="mt-[50px]">
                        <input
                          type="file"
                          id="profileImage"
                          {...register("profileImage", { required: false })}
                          onChange={({ target }) => {
                            if (target.files) {
                              const file = target.files[0];

                              setSelectedFile(file);
                            }
                          }}
                        />
                        {errors.profileImage && imageSelect && (
                          <p className="text-red-700 error">
                            Enter a profile image.
                          </p>
                        )}
                      </div>
                    )}
                    <div>
                     {/* { payload.profileImage &&
                       <Image
                        src={`${payload.profileImage}`}
                        // src="https://th.bing.com/th/id/OIP.avb9nDfw3kq7NOoP0grM4wHaEK?pid=ImgDet&rs=1"
                        className="w-32 h-32 mx-auto transition duration-200 transform border-4 border-white rounded-full hover:scale-110"
                        alt="Avatar Image"
                        width={25}
                        height={25}
                      />
                     } */}
                    </div>
                  </div>
                </div>
              ) : (
                ""
              )}

              {/*footer*/}
              <div className="flex items-center justify-center p-6 border-t border-solid rounded-b border-slate-200">
                <button
                  className="px-6 py-3 mb-1 mr-1 text-[16px] font-bold text-white uppercase transition-all duration-150 ease-linear rounded shadow outline-none bg-purple active:bg-purple hover:shadow-lg focus:outline-none"
                  type="submit"
                  // onClick={onRequestClose}
                >
                  Save Changes
                </button>
              </div>
              {/* <div className="flex items-center justify-center p-6 border-t border-solid rounded-b border-slate-200">
                <Modalbutton
                  onRequestClose={onRequestClose}
                  buttonclassname="px-6 py-3 mb-1 mr-1 text-[16px] font-bold text-white uppercase transition-all duration-150 ease-linear rounded shadow outline-none bg-purple active:bg-purple hover:shadow-lg focus:outline-none"
                  type="button"
                  buttontext="Save Changes"
                />
              </div> */}
            </div>
          </div>
        </div>
      </form>
      {/* <div className="fixed inset-0 z-40 bg-black opacity-25"></div> */}
    </>
  );
};

export default Modal;
