import React, {useEffect, useState} from "react";
import {
    Button,
    HStack,
    Menu,
    MenuButton,
    MenuItem,
    MenuList,
    Stack,
    Table,
    Tbody,
    Td,
    Thead,
    Tr,
    useToast,
} from "@chakra-ui/react";
import Header from "./Header";
import {deleteRecordByPrimaryKey, getSearchQuery} from "./../utils/GenericQueries";
import {useMutation, useQuery} from "@apollo/client";
import {ChevronDownIcon} from "@chakra-ui/icons";
import ConfirmDialog from "../Custom/ConfirmDialog";
import {getSinglePrimaryKey} from "./../utils/CustomeTableUtils";


const PodcastTable = (props: any) => {
    const toast = useToast();

    const {tablename, col, refetchdata} = props;
    const searchQuery = getSearchQuery(tablename, col);
    const {loading, error, data, refetch} = useQuery(searchQuery);


    const {setIsSelected, editRecord, createRecord} = props;

    const [deleteRecord] = useMutation(deleteRecordByPrimaryKey(tablename, col));
    const [itemToBeDeleted, setItemToBeDeleted] = useState(null)
    const [isDialogOpen, setDialogOpen] = useState(false);


    useEffect(() => {
        if (refetchdata) {
            refetch();
        }
    }, [refetchdata])


    function enableCreate(e: any) {
        setIsSelected(true);
        createRecord();
    }

    function handleEdit(item: any) {
        setIsSelected(true)
        editRecord(item)
    }

    function handleDelete(item: any) {
        setItemToBeDeleted(item);
        setDialogOpen(true);
    }

    function deleteCallBack(shouldItemBeDeleted: any) {
        setDialogOpen(false);
        if (itemToBeDeleted == null)
            return;

        if (shouldItemBeDeleted) {
            let primaryKey = getSinglePrimaryKey(col)
            let deleteObj = {
                [primaryKey]: itemToBeDeleted[primaryKey]
            }
            deleteRecord({
                variables: deleteObj
            }).then(r => {
                toast({
                    title: 'Deleted',
                    status: 'success',
                    duration: 3000,
                    isClosable: true,
                });

                refetch();
            }).catch(e => {
                console.log("error ", e)
                toast({
                    title: "Error",
                    description: e.message,
                    status: "error",
                    duration: 3000,
                    isClosable: true
                })
            })
        }
    }


    if (loading) {
        return <div>Loading...</div>;
    }
    if (error) {
        console.log("error ", error);

        return <div>Error...</div>;
    }
    if (data)
        return (
            <>
                <Stack
                    w="100%"
                    h="100%"
                    alignItems={"center"}
                    pb="40px"
                    bg="rgba(247, 248, 252, 1)"
                >
                    <Header title="Podcasts" isBack={false}/>
                    <HStack justifyContent="right" w="100%" px="5%">
                        <Button
                            w="150px"
                            h="46px"
                            color="white"
                            bg="#051E61"
                            fontFamily="MaisonBold"
                            fontSize="14px"
                            fontStyle="normal"
                            fontWeight="700"
                            lineHeight="14px"
                            letterSpacing="0.20000001192092896px"
                            _hover={{bg: "blue.900"}}
                            onClick={enableCreate}
                        >
                            Create new Podcast
                        </Button>
                    </HStack>
                    <Table
                        maxW={"1121px"}
                        size="sm"
                        variant="none"
                        border="1px solid "
                        bg="white"
                        borderColor="rgba(223, 224, 235, 1)"
                    >
                        <Thead
                            h="44px"
                            borderBottom="1px solid"
                            borderColor="rgba(223, 224, 235, 1)"
                        >
                            <Tr>
                                <Td fontSize="12px" className="Masion-Book" color="#9FA2B4">
                                    Category
                                </Td>
                                <Td fontSize="12px" className="Masion-Book" color="#9FA2B4">
                                    Title
                                </Td>
                                <Td
                                    fontSize="12px"
                                    textAlign="center"
                                    className="Masion-Book"
                                    color="#9FA2B4"
                                >
                                    Publish Date
                                </Td>

                                <Td
                                    fontSize="12px"
                                    textAlign="center"
                                    className="Masion-Book"
                                    color="#9FA2B4">
                                    Actions
                                </Td>

                            </Tr>
                        </Thead>
                        <Tbody>

                            {data[`${tablename}`].map((item: any) => (
                                <Tr
                                    h="60px"
                                    borderBottom="1px solid"
                                    borderColor="rgba(223, 224, 235, 1)"
                                    cursor="pointer"
                                >
                                    <Td
                                        className="MasionDemi"
                                        textAlign="left"
                                        fontSize="14px"
                                        color="black"
                                    >
                                        {item.category}
                                    </Td>
                                    <Td>
                                        {item.title}
                                    </Td>
                                    <Td
                                        className="interFonts"
                                        textAlign="center"
                                        fontWeight="500"
                                        fontSize="13px"
                                        color="black"
                                    >
                                        {item.publish_date}
                                    </Td>

                                    <Td className="interFonts"
                                        textAlign="center"
                                        fontWeight="500"
                                        fontSize="13px"
                                        color="black">
                                        <Menu>
                                            <MenuButton bg="transparent" as={Button} rightIcon={<ChevronDownIcon/>}>
                                                Actions
                                            </MenuButton>
                                            <MenuList>
                                                <MenuItem onClick={() => handleEdit(item)}>Edit</MenuItem>
                                                <MenuItem onClick={() => handleDelete(item)}>Delete</MenuItem>
                                            </MenuList>
                                        </Menu>
                                    </Td>


                                </Tr>
                            ))
                            }


                        </Tbody>
                    </Table>
                </Stack>

                <ConfirmDialog
                    isOpen={isDialogOpen}
                    callBack={deleteCallBack}
                    confirmText='Are you sure?'
                    cancelBtnText='Cancel'
                    headerText='Delete Podcast'
                    confirmBtnText='Confirm'
                />

            </>
        );
    return <div>No Data</div>;

};

export default PodcastTable;
