import {Button, Grid, GridItem, HStack, Input, Stack, useToast} from "@chakra-ui/react"
import {convertColTypeToInputType, underScoreToCapitalize,} from "../utils/TransformText";
import React, {useState} from "react";
import {addTableRecord, updateTableByPrimaryKey,} from "../utils/GenericQueries";

import {getSinglePrimaryKey} from "../utils/CustomeTableUtils";
import DropdownSelect from "../Dropdown";
import CustomStaticDropDown from "./CustomStaticDropDown";
import {PhotoUpload} from "../Babbu/PhotoUpload";

import {useMutation} from "@apollo/client";
import {Text} from "@chakra-ui/layout";
import {inputCardProps} from "./FormColDesign";
import {Col} from "../intefaces/interfaces";

interface AddEditFormColProps {
    title: string;
    tablename: string;
    col: Col[];
    noOfCols: number;
    formdata: any;
    isUpdate: boolean;
    close: () => void;
    refetch: () => void;
}

function AddEditFormCol(props: AddEditFormColProps) {
    const toast = useToast()

    const {title, tablename, col, isUpdate} = 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 handleChangeSelect(value: any, field: string) {
        let formDataTemp = {...formdata};
        formDataTemp[field] = value;
        setFormData(formDataTemp);
    }


    function save(e: any) {
        if (isSaving) {
            return;
        }
        delete formdata["__typename"];
        setIsSaving(true)
        if (isUpdate) {
            updateByPrimaryKey({
                variables: formdata
            }).then(res => {
                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 => {
                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 checkForStaticDropDown(tablecolField: any) {
        if (typeof tablecolField.staticDropDown !== 'undefined' && tablecolField.staticDropDown) {
            return true
        }
        return false
    }

    function isImage(tablecolField: any) {
        if (tablecolField?.type == 'image' || tablecolField?.type == 'image!') {
            return true
        }
        return false
    }

    let arrInputs = [
        {
            label: "CTA Button Title",
            placeholder: "Enter the title of your button i.e. Redeem",
            spacing: "0"
        },
        {
            label: "CTA Button Title 2",
            placeholder: "Enter the title of your button i.e. Redeem 2",
            spacing: "1"
        },
        {
            label: "CTA Button Title 3",
            placeholder: "Enter the title of your button i.e. Redeem 3",
            spacing: "2"
        }
    ];

    return (
        <>
            {/*<PanelForm*/}
            {/*    title="CTA Styling"*/}
            {/*    inputs={arrInputs}*/}
            {/*    noOfCols={props.noOfCols}*/}
            {/*    onChange={(e: any) => {*/}
            {/*        console.log(e.target.value);*/}
            {/*    }}*/}
            {/*/>*/}
            <>
                <Stack
                    w="100%"
                    justifyContent={"space-between"}
                    border="1px solid #C4C4C4"
                    py="12px"
                    px="24px"
                    borderRadius={"4px"}
                >
                    <Text
                        fontFamily={"Inter"}
                        fontWeight={"700"}
                        fontStyle={"normal"}
                        fontSize={"17px"}
                        lineHeight={"20.57px"}
                        color="#4138C2"
                    >
                        {title}
                    </Text>
                    <Grid templateColumns={`repeat(${props.noOfCols}, 1fr)`} gap={6}>
                        {col.map((tablecolField: any) => {
                            return (
                                <GridItem w={"100%"}>
                                    <Text
                                        fontFamily={"Inter"}
                                        fontWeight={"700"}
                                        fontStyle={"normal"}
                                        fontSize={"13px"}
                                        lineHeight={"18px"}
                                        color="black"
                                        mb={"5px"}
                                    >
                                        {underScoreToCapitalize(tablecolField.name)}
                                    </Text>

                                    {tablecolField.isForeignKey &&
                                    <DropdownSelect
                                        tableName={tablecolField.tableName}
                                        cols={tablecolField.cols}
                                        placeholder={tablecolField.placeholder}
                                        returnColumn={tablecolField.returnColumn}
                                        displayColumns={tablecolField.displayColumns}
                                        defaultValue={formdata[tablecolField.name]}
                                        OnChange={(val: any) => {
                                            handleChangeSelect(val, tablecolField.name)
                                        }}
                                    />
                                    }
                                    {!tablecolField.isForeignKey && (isImage(tablecolField)) &&
                                    <HStack>
                                        <PhotoUpload
                                            label={underScoreToCapitalize(tablecolField.name)}
                                            onUpload={(file: any) => {
                                                let formDataTemp = {...formdata};
                                                formDataTemp[tablecolField.name] = file;
                                                setFormData(formDataTemp);
                                            }}
                                        />
                                    </HStack>
                                    }

                                    {checkForStaticDropDown(tablecolField) ?
                                        <CustomStaticDropDown
                                            value={getFieldData(tablecolField.name)}
                                            options={tablecolField.staticDropDown}
                                            placeholder={underScoreToCapitalize(tablecolField.name)}

                                            OnChange={(val: any) => {
                                                handleChangeSelect(val, tablecolField.name)
                                            }}
                                        />
                                        :
                                        <Input
                                            display={(isImage(tablecolField) || tablecolField.isForeignKey) ? 'none' : 'block'}
                                            type={convertColTypeToInputType(tablecolField.type)}
                                            readOnly={tablecolField.isPrimary}
                                            onChange={(e) => {
                                                handleChange(e, tablecolField.name)
                                            }}
                                            value={getFieldData(tablecolField.name)}

                                            h="38px"
                                            border="1px solid "
                                            borderColor={"#ACABAB"}
                                            borderRadius={"4px"}
                                            placeholder={underScoreToCapitalize(tablecolField.name)}
                                        />
                                    }

                                </GridItem>

                            )
                        })
                        }

                        {/*{arrInputs.map((input, index) => {*/}
                        {/*    return (*/}
                        {/*        <GridItem*/}
                        {/*            w={"100%"}>*/}
                        {/*            <Text*/}
                        {/*                fontFamily={"Inter"}*/}
                        {/*                fontWeight={"700"}*/}
                        {/*                fontStyle={"normal"}*/}
                        {/*                fontSize={"13px"}*/}
                        {/*                lineHeight={"18px"}*/}
                        {/*                color="black"*/}
                        {/*            >*/}
                        {/*                {input.label}*/}
                        {/*            </Text>*/}
                        {/*            <Input*/}
                        {/*                w="529px"*/}
                        {/*                h="38px"*/}
                        {/*                border="1px solid "*/}
                        {/*                borderColor={"#ACABAB"}*/}
                        {/*                borderRadius={"4px"}*/}
                        {/*                placeholder={input.placeholder}*/}
                        {/*            />*/}
                        {/*        </GridItem>*/}

                        {/*    )*/}
                        {/*})*/}
                        {/*}*/}
                    </Grid>


                    <HStack
                        justify={"flex-end"}
                        spacing="6px">
                        <Button
                            onClick={() => {
                                props.close()
                            }}
                            disabled={isSaving}

                            fontWeight="700"
                            fontSize="12px"
                            color="black"
                            border="1px"
                            className="interFonts"
                            w="100px"
                            h="30px"
                            bg=""
                            alignSelf="flex-end"
                            borderRadius="2.89px"
                            _hover={{color: "#009CC4", bg: "white", border: "1px solid #009CC4"}}
                        >
                            Cancel
                        </Button>
                        <Button
                            isLoading={isSaving}
                            onClick={save}
                            fontWeight="700"
                            fontSize="12px"
                            color="white"
                            border="1px"
                            className="interFonts"
                            w="100px"
                            h="30px"
                            bg="#009CC4"
                            alignSelf="flex-end"
                            borderRadius="2.89px"
                            _hover={{color: "#009CC4", bg: "white", border: "1px solid #009CC4"}}

                        >
                            Save
                        </Button>

                    </HStack>

                </Stack>
            </>


            {/*<Stack*/}
            {/*    w={"50vw"}*/}
            {/*    p={"2"}*/}
            {/*    border={"1px"}*/}
            {/*    borderColor={"gray.200"}*/}
            {/*    spacing="19px">*/}

            {/*    <Text textAlign="left" className="interFonts" fontWeight="700" color="black" fontSize="16px">*/}
            {/*        {title}*/}
            {/*    </Text>*/}

            {/*    {col.map((tablecolField: any) => {*/}
            {/*        return (*/}
            {/*            <>*/}
            {/*                {tablecolField.isForeignKey &&*/}
            {/*                <FormControl>*/}
            {/*                    <DropdownSelect*/}
            {/*                        tableName={tablecolField.tableName}*/}
            {/*                        cols={tablecolField.cols}*/}
            {/*                        placeholder={tablecolField.placeholder}*/}
            {/*                        returnColumn={tablecolField.returnColumn}*/}
            {/*                        displayColumns={tablecolField.displayColumns}*/}
            {/*                        defaultValue={formdata[tablecolField.name]}*/}
            {/*                        OnChange={(val: any) => {*/}
            {/*                            handleChangeSelect(val, tablecolField.name)*/}
            {/*                        }}*/}
            {/*                    />*/}
            {/*                </FormControl>*/}
            {/*                }*/}

            {/*                {!tablecolField.isForeignKey && (tablecolField.type == 'image' || tablecolField.type == 'image!') &&*/}
            {/*                <HStack>*/}
            {/*                    <PhotoUpload*/}
            {/*                        label={underScoreToCapitalize(tablecolField.name)}*/}
            {/*                        onUpload={(file: any) => {*/}
            {/*                            let formDataTemp = {...formdata};*/}
            {/*                            formDataTemp[tablecolField.name] = file;*/}
            {/*                            setFormData(formDataTemp);*/}
            {/*                        }}*/}
            {/*                    />*/}
            {/*                </HStack>*/}
            {/*                }*/}

            {/*                {checkForStaticDropDown(tablecolField) ?*/}
            {/*                    <CustomStaticDropDown*/}
            {/*                        value={getFieldData(tablecolField.name)}*/}
            {/*                        options={tablecolField.staticDropDown}*/}
            {/*                        placeholder={underScoreToCapitalize(tablecolField.name)}*/}


            {/*                        OnChange={(val: any) => {*/}
            {/*                            handleChangeSelect(val, tablecolField.name)*/}
            {/*                        }}*/}
            {/*                    />*/}
            {/*                    :*/}
            {/*                    <HStack alignItems="center">*/}
            {/*                        <Text*/}
            {/*                            w={"15%"}*/}
            {/*                            className="interFonts"*/}
            {/*                            fontWeight="500"*/}
            {/*                            fontSize="13px"*/}
            {/*                            color="#626D85"*/}
            {/*                            textAlign="right">*/}
            {/*                            {underScoreToCapitalize(tablecolField.name)}*/}
            {/*                        </Text>*/}
            {/*                        <Input*/}
            {/*                            w={"85%"}*/}
            {/*                            type={convertColTypeToInputType(tablecolField.type)}*/}
            {/*                            readOnly={tablecolField.isPrimary}*/}
            {/*                            onChange={(e) => {*/}
            {/*                                handleChange(e, tablecolField.name)*/}
            {/*                            }}*/}
            {/*                            value={getFieldData(tablecolField.name)}*/}
            {/*                        />*/}
            {/*                    </HStack>*/}
            {/*                }*/}


            {/*            </>*/}

            {/*        )*/}
            {/*    })*/}
            {/*    }*/}


            {/*    <HStack*/}
            {/*        justify={"flex-end"}*/}
            {/*        spacing="6px">*/}
            {/*        <Button*/}
            {/*            onClick={() => {*/}
            {/*                props.close()*/}
            {/*            }}*/}
            {/*            disabled={isSaving}*/}

            {/*            fontWeight="700"*/}
            {/*            fontSize="12px"*/}
            {/*            color="black"*/}
            {/*            border="1px"*/}
            {/*            className="interFonts"*/}
            {/*            w="76px"*/}
            {/*            h="28px"*/}
            {/*            bg=""*/}
            {/*            alignSelf="flex-end"*/}
            {/*            borderRadius="2.89px"*/}
            {/*            _hover={{color: "#009CC4", bg: "white", border: "1px solid #009CC4"}}*/}

            {/*        >*/}
            {/*            Cancel*/}
            {/*        </Button>*/}

            {/*        <Button*/}
            {/*            isLoading={isSaving}*/}
            {/*            onClick={save}*/}
            {/*            fontWeight="700"*/}
            {/*            fontSize="12px"*/}
            {/*            color="white"*/}
            {/*            border="1px"*/}
            {/*            className="interFonts"*/}
            {/*            w="76px"*/}
            {/*            h="28px"*/}
            {/*            bg="#009CC4"*/}
            {/*            alignSelf="flex-end"*/}
            {/*            borderRadius="2.89px"*/}
            {/*            _hover={{color: "#009CC4", bg: "white", border: "1px solid #009CC4"}}*/}

            {/*        >*/}
            {/*            Save*/}
            {/*        </Button>*/}

            {/*    </HStack>*/}


            {/*</Stack>*/}
        </>
    )
}


const PanelForm = (props: inputCardProps) => {
    return (
        <>
            <Stack
                w="100%"
                justifyContent={"space-between"}
                border="1px solid #C4C4C4"
                py="12px"
                px="24px"
                borderRadius={"4px"}
            >
                <Text
                    fontFamily={"Inter"}
                    fontWeight={"700"}
                    fontStyle={"normal"}
                    fontSize={"17px"}
                    lineHeight={"20.57px"}
                    color="#4138C2"
                >
                    {props.title}
                </Text>
                <Grid templateColumns={`repeat(${props.noOfCols}, 1fr)`} gap={6}>
                    {props.inputs.map((input, index) => {
                        return (
                            <GridItem
                                w={"100%"}>
                                <Text
                                    fontFamily={"Inter"}
                                    fontWeight={"700"}
                                    fontStyle={"normal"}
                                    fontSize={"13px"}
                                    lineHeight={"18px"}
                                    color="black"
                                >
                                    {props.inputs[index].label}
                                </Text>
                                <Input
                                    w="529px"
                                    h="38px"
                                    border="1px solid "
                                    borderColor={"#ACABAB"}
                                    borderRadius={"4px"}
                                    placeholder={props.inputs[index].placeholder}
                                />
                            </GridItem>

                        )
                    })
                    }
                </Grid>


                {/*{props.inputs.map((input, index) => {*/}
                {/*    return (*/}
                {/*        <Grid templateColumns='repeat(2, 1fr)' gap={6}>*/}
                {/*                <GridItem*/}
                {/*                    bg={"blue.200"}*/}
                {/*                    w={"100%"}>*/}
                {/*                    <Text*/}
                {/*                        fontFamily={"Inter"}*/}
                {/*                        fontWeight={"700"}*/}
                {/*                        fontStyle={"normal"}*/}
                {/*                        fontSize={"13px"}*/}
                {/*                        lineHeight={"18px"}*/}
                {/*                        color="black"*/}
                {/*                    >*/}
                {/*                        {props.inputs[index].label}*/}
                {/*                    </Text>*/}
                {/*                    <Input*/}
                {/*                        w="529px"*/}
                {/*                        h="38px"*/}
                {/*                        border="1px solid "*/}
                {/*                        borderColor={"#ACABAB"}*/}
                {/*                        borderRadius={"4px"}*/}
                {/*                        placeholder={props.inputs[index].placeholder}*/}
                {/*                    />*/}
                {/*                </GridItem>*/}
                {/*        </Grid>*/}
                {/*    )*/}
                {/*})}*/}
            </Stack>
        </>
    );
};

export default AddEditFormCol

