import React, {useState} from "react";
import "../../index.css";
import {Button, HStack, Stack, useToast,} from "@chakra-ui/react";
import Header from "./Header";
import {CustomInput, CustomInputDate} from "./CustomComponents";

import TextBox from "./TextBox";
import {addTableRecord, updateTableByPrimaryKey} from "./../utils/GenericQueries";
import {useMutation} from "@apollo/client";
import {getSinglePrimaryKey} from "./../utils/CustomeTableUtils";
import {PhotoUpload} from "./PhotoUpload";
import {VideoUpload} from "./VideoUpload";

let uploadIcon =
    "https://firebasestorage.googleapis.com/v0/b/imagestorage-7b2d2.appspot.com/o/uploadIcon.svg?alt=media&token=5c5650be-aa0e-49de-9bc7-dcf1d706d1e3";

interface inputProps {
    title: string;
    OnChange: any;
}

const CreateVideo = (props: any) => {
    const toast = useToast();

    const {title, tablename, col, isUpdate, goBack} = props
    const [formdata, setFormData] = useState(props.formdata);

    const [isSaving, setIsSaving] = useState(false);
    const updatebyPk = updateTableByPrimaryKey(tablename, col)

    const [updateByPrimaryKey] = useMutation(updatebyPk);

    const [addRecord] = useMutation(addTableRecord(tablename, col));

    function getFieldData(field: string) {
        return formdata[field]
    }

    function handleChange(e: any, field: string) {
        const {value} = e.target;
        let formDataTemp = {...formdata};
        formDataTemp[field] = value;
        setFormData(formDataTemp);
    }

    function handleChangeValue(value: any, field: string) {
        let formDataTemp = {...formdata};
        formDataTemp[field] = value;
        setFormData(formDataTemp);
    }


    function save(e: any) {
        if (isSaving) {
            return;
        }
        setIsSaving(true)
        if (isUpdate) {
            updateByPrimaryKey({
                variables: formdata
            }).then(res => {
                toast({
                    title: "Success",
                    description: 'updated.',
                    status: "success",
                    duration: 9000,
                    isClosable: true
                })
                setIsSaving(false)
                props.refetch();

            }).catch(e => {
                toast({
                    title: "Error",
                    description: e.message,
                    status: "error",
                    duration: 9000,
                    isClosable: true
                })
                setIsSaving(false)
                console.log("error ", e)
            })
        } else {
            //remove primary key
            let singlePrimaryKeyCol = getSinglePrimaryKey(col);
            delete formdata[singlePrimaryKeyCol];

            //ADD RECORD
            addRecord({
                variables: {
                    object: formdata
                }
            }).then(r => {
                toast({
                    title: "Success",
                    description: 'saved.',
                    status: "success",
                    duration: 9000,
                    isClosable: true
                })
                setIsSaving(false)
                props.refetch();
            }).catch(e => {
                setIsSaving(false)
                console.log("error ", e)
                toast({
                    title: "Error",
                    description: e.message,
                    status: "error",
                    duration: 9000,
                    isClosable: true
                })
            })

        }
    }

    function getTitle() {
        return isUpdate ? "Update Video" : "Create Video"
    }

    return (
        <>
            <Stack
                w="100%"
                bg="rgba(247, 248, 252, 1)"
                h="auto"
                spacing="48px"
                alignItems={"center"}
            >
                <Header
                    title={getTitle()}
                    goBack={goBack}/>
                <Stack w="100%" alignItems={"center"} pb="80px">
                    <Stack spacing={"32px"} minWidth={"545px"}>
                        <CustomInput
                            title="Category"
                            OnChange={(e: any) => {
                                handleChange(e, "category")
                            }}
                            value={getFieldData("category")}
                        />
                        <CustomInput
                            title="Title"
                            OnChange={(e: any) => {
                                handleChange(e, "title")
                            }}
                            value={getFieldData("title")}
                        />
                        <VideoUpload
                            onUpload={(url: any) => {
                                handleChangeValue(url, "video")
                            }}
                        />
                        <PhotoUpload
                            onUpload={(url: any) => {
                                handleChangeValue(url, "poster_image")
                            }}
                        />


                        <TextBox
                            OnChange={(value: any) => {
                                handleChangeValue(value, "content")
                            }}
                            value={getFieldData("content")}
                        />

                        <CustomInputDate
                            title="Publish Date"
                            OnChange={(e: any) => {
                                handleChange(e, "publish_date")
                            }}
                            value={getFieldData("publish_date")}
                        />
                    </Stack>
                    <HStack py="32px" justifyContent="right" w="545px">
                        <Button
                            isLoading={isSaving}
                            onClick={save}
                            w="136px"
                            h="46px"
                            color="white"
                            bg="#051E61"
                            fontFamily="MaisonBold"
                            fontSize="14px"
                            fontStyle="normal"
                            fontWeight="700"
                            lineHeight="14px"
                            letterSpacing="0.20000001192092896px"
                        >
                            Post Video
                        </Button>
                    </HStack>
                </Stack>
            </Stack>
        </>
    );
};

export default CreateVideo;
