import React, {useState} from "react";
import {Button, HStack, Stack, useToast,} from "@chakra-ui/react";
import Header from "./Header";
import {CustomInput, CustomInputDate} from "./CustomComponents";
import {addTableRecord, updateTableByPrimaryKey} from "./../utils/GenericQueries";
import {useMutation} from "@apollo/client";
import {getSinglePrimaryKey} from "./../utils/CustomeTableUtils";
import {PhotoUpload} from "./PhotoUpload";
import {AudioUpload} from "./AudioUpload";


interface inputProps {
    title: string;
    OnChange: any;
}

const CreateProdcast = (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 handleChangeImage(url: any, field: string) {
        let value = url;
        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 Podcast" : "Create Podcast"
    }

    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")}
                        />

                        <AudioUpload
                            onUpload={(url: any) => {
                                handleChangeImage(url, "audio")
                            }}
                        />


                        <PhotoUpload
                            onUpload={(url: any) => {
                                handleChangeImage(url, "poster_image")
                            }}
                        />

                        <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 Prodcast
                        </Button>
                    </HStack>
                </Stack>
            </Stack>
        </>
    );
};

export default CreateProdcast;
