
    import React, { useEffect, useState } from "react";
    import { useForm } from "react-hook-form";
    import { yupResolver } from "@hookform/resolvers/yup";
    import * as yup from "yup";
    import MkdSDK from "Utils/MkdSDK";
    import { useNavigate, useParams } from "react-router-dom";
    import { AuthContext, tokenExpireError } from "Context/Auth";
    import { GlobalContext, showToast } from "Context/Global";
    import ReactQuill from 'react-quill';
    import 'react-quill/dist/quill.snow.css';
    import { isImage, empty, isVideo, isPdf } from "Utils/utils";
    import {MkdInput} from "Components/MkdInput";
import {InteractiveButton} from "Components/InteractiveButton"
import { SkeletonLoader } from "Components/Skeleton";


    let sdk = new MkdSDK();

    const EditItemMovementHistoryPage = () => {
    const { dispatch } = React.useContext(AuthContext);
    const schema = yup
        .object({
    
        	product_id: yup.string(),
        	moved_from: yup.string(),
        	moved_to: yup.string(),
        	date: yup.string(),
        })
        .required();
    const { dispatch: globalDispatch } = React.useContext(GlobalContext);
    const [fileObj, setFileObj] = React.useState({});
    const [isLoading, setIsLoading] = React.useState(true)
    const [loading, setLoading] = React.useState(false)

    const navigate = useNavigate();
    
          	const [product_id, setProductId] = useState(0);
          	const [moved_from, setMovedFrom] = useState('');
          	const [moved_to, setMovedTo] = useState('');
          	const [date, setDate] = useState('');
    // const [id, setId] = useState(0);
    const {
        register,
        handleSubmit,
        setError,
        setValue,
        formState: { errors },
    } = useForm({
        resolver: yupResolver(schema),
    });

    const params = useParams();

    useEffect(function () {
        (async function () {
        try {
            setLoading(true)

            sdk.setTable("item_movement_history");
            const result = await sdk.callRestAPI({ id: Number(params?.id)}, "GET");
            if (!result.error) {
    
        	 setValue('product_id', result.model.product_id);
        	 setValue('moved_from', result.model.moved_from);
        	 setValue('moved_to', result.model.moved_to);
        	 setValue('date', result.model.date);

    
      	 setProductId(result.model.product_id);
      	 setMovedFrom(result.model.moved_from);
      	 setMovedTo(result.model.moved_to);
      	 setDate(result.model.date);
                setId(result.model.id);
                setLoading(false)

            }
        } catch (error) {
            setLoading(false)

            console.log("error", error);
            tokenExpireError(dispatch, error.message);
        }
        })();
    }, []);

    const previewImage = (field, target) => {
        let tempFileObj = fileObj;
        tempFileObj[field] = {
        file: target.files[0],
        tempURL: URL.createObjectURL(target.files[0]),
        };
        setFileObj({ ...tempFileObj });
    };


    const onSubmit = async (_data) => {
        setIsLoading(true)
        try {
            sdk.setTable("item_movement_history");
        for (let item in fileObj) {
            let formData = new FormData();
            formData.append('file', fileObj[item].file);
            let uploadResult = await sdk.uploadImage(formData);
            _data[item] = uploadResult.url;
            
        }
        const result = await sdk.callRestAPI(
            {
            id: id,
            
        		product_id: _data.product_id,
        		moved_from: _data.moved_from,
        		moved_to: _data.moved_to,
        		date: _data.date,

       
            },
            "PUT"
        );

        if (!result.error) {
            showToast(globalDispatch, "Updated");
            navigate("/admin/item_movement_history");
        } else {
            if (result.validation) {
            const keys = Object.keys(result.validation);
            for (let i = 0; i < keys.length; i++) {
                const field = keys[i];
                setError(field, {
                type: "manual",
                message: result.validation[field],
                });
            }
            }
        }
        setIsLoading(false)
        } catch (error) {
            setIsLoading(false)
        console.log("Error", error);
        setError("product_id", {
            type: "manual",
            message: error.message,
        });
        }
    };
    React.useEffect(() => {
        globalDispatch({
        type: "SETPATH",
        payload: {
            path: "item_movement_history",
        },
        });
    }, []);

    return (
        <div className=" shadow-md rounded   mx-auto p-5">
        <h4 className="text-2xl font-medium">Edit Item Movement History</h4>
       {loading? (<SkeletonLoader/>) :  (<form className=" w-full max-w-lg" onSubmit={handleSubmit(onSubmit)}>
            
            
      <MkdInput
      type={"number"}
      page={"edit"}
      name={"product_id"}
      errors={errors}
      label={"Product Id"}
      placeholder={"Product Id"}
      register={register}
      className={""}
    />
          
        
            
      <MkdInput
      type={"text"}
      page={"edit"}
      name={"moved_from"}
      errors={errors}
      label={"Moved From"}
      placeholder={"Moved From"}
      register={register}
      className={""}
    />
        
            
      <MkdInput
      type={"text"}
      page={"edit"}
      name={"moved_to"}
      errors={errors}
      label={"Moved To"}
      placeholder={"Moved To"}
      register={register}
      className={""}
    />
        
            
            <MkdInput
            type={"date"}
            page={"edit"}
            name={"date"}
            errors={errors}
            label={"Date"}
            placeholder={"Date"}
            register={register}
            className={""}
          />
        
            <InteractiveButton
            type="submit"
            className="bg-primaryBlue text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
            loading={isLoading}
            disable={isLoading}
            >
            Submit
            </InteractiveButton>
        </form>)}
        </div>
    );
    };

    export default EditItemMovementHistoryPage;

    