import React, { useCallback, useRef, useState } from 'react'
import {
    createColumnHelper,
    getCoreRowModel,
    useReactTable,
    getSortedRowModel
} from '@tanstack/react-table'
import { useMutation, useQuery, useQueryClient } from 'react-query'
import { Button, Dropdown, Form, InputGroup, Modal } from 'react-bootstrap'
import {  useForm } from 'react-hook-form'
import ReactTable from '../../components/ReactTable'
import Pagination from '../../components/Pagination'
import requestApi from '../../utils/request'
import Swal from 'sweetalert2'
import { ReactComponent as Eyes } from '../../assets/images/teyes.svg'
import { ReactComponent as Edit } from '../../assets/images/tedit.svg'
import { ReactComponent as Delete } from '../../assets/images/tdelete.svg'
import { ReactComponent as DeleteImg } from '../../assets/images/redbin.svg'
import { ReactComponent as SearchIcon } from '../../assets/images/greysearch.svg'
import { ReactComponent as FilterIcon } from '../../assets/images/filter.svg'
import { employerview, jobopeningview } from '../../Routes/routingConsts'
import DropDownControl from '../../components/DropDownControl/DropDownControl'
import SpinnerLoader from '../../components/SpinnerLoader'
import { Spinner } from 'react-bootstrap'
import { useEffect } from 'react'
import { deleteActionIcon, viewIcon, editactionIcon } from '../../functions/actionIcons'
import FlottedButton from '../../components/FlottingButton'
import ButtonWithLoader from '../../components/ButtonWithLoader/ButtonWithLoader'
import InputControl from '../../components/InputControl/InputControl'

const FaqCategoryManagement = () => {
    const [toggle, setToggle] = useState(null)
    const queryClient = useQueryClient()
    const [DataLimit, setDataLimit] = useState(10)
    const [currentPage, setCurrentPage] = useState(1)
    const EditDataRef = useRef(null);
    const [userFilterText, setuserFilterText] = useState('')
    const handleChange2 = (e) => {
        setCurrentPage(1)
        const getData = setTimeout(() => {
            setuserFilterText(e.target.value)
        }, 1000)
        clearInterval()
    }

    const handleChange = (eventkey) => {
        setDataLimit(eventkey)
    }

    function editjobopening(categoryItem) {
        setShowAdd(true)
        EditDataRef.current = categoryItem.categoryId
        setAddCategoryValue(categoryItem.categoryName)
    }

    /////status filter////
    const [statusControl, setStatusControl] = useState('')
    const handleChangeStatus = (eventKey) => {
        setCurrentPage(1)
        setStatusControl(eventKey)
    }
    ////end///
    const {
        register,
        handleSubmit,
        reset,
        getValues,
        control,
        formState: { errors }
    } = useForm()

    const [sorting, setSorting] = useState([])

    function UserList({ queryKey }) {
        return requestApi
            .post(
                `/faqCategory/list`,
                {
                    search: queryKey[3],
                    limit: queryKey[2],
                    page: queryKey[1],
                    sortKey: queryKey[4]?.id ?? '',
                    sortBy: queryKey[4] ? (queryKey[4]?.desc ? -1 : 1) : '',
                    status: statusControl
                },
                { headers: true }
            )
            .then((res) => {
                return res.data
            })
    }
    const { data, isLoading } = useQuery({
        queryKey: [
            'faqcategorylist',
            currentPage,
            DataLimit,
            userFilterText,
            sorting[0],
            statusControl
        ],
        queryFn: UserList
        // select: () => {
        //     return {
        //         data: null
        //     }
        // }
    })

    let totalJobOpening = data?.meta?.totalCount

    const handleChangePage = useCallback(
        (currentPage) => {
            setCurrentPage(currentPage)
        },
        [currentPage]
    )

    const columnHelper = createColumnHelper()
    const columns = [
        columnHelper.display({
            id: 'actions',
            header: 'Action',
            cell: (row) => {
                return (
                    <>
                        <div className="">
                            <FlottedButton
                                clickFn={() => {
                                    setToggle((pre) =>
                                        pre === row.row.original?.categoryId
                                            ? null
                                            : row.row.original?.categoryId
                                    )
                                }}
                                isTrue={
                                    row.row.original?.categoryId === toggle
                                }
                            >
                                {row.row.original.status === 3 ? (
                                    ''
                                ) : (
                                    // <li
                                    //     className=" i1 icon"
                                    //     onClick={() =>
                                    //         viewjobopeningData(
                                    //             row.row.original?.categoryId
                                    //         )
                                    //     }
                                    // >
                                    //     {viewIcon}
                                    // </li>
                                    ''
                                )}
                                <li
                                        className=" i1 icon"
                                        onClick={() =>{
                                            editjobopening(
                                                row.row.original
                                            )
                                            
                                        }
                                            
                                        }
                                    >
                                        {editactionIcon}
                                    </li>
                              
                                {row.row.original.status === 3 ? (
                                    ''
                                ) : (
                                    <li
                                        className=" i1 icon"
                                        onClick={() =>
                                            hanleDeleteModal(
                                                row.row.original?.categoryId
                                            )
                                        }
                                    >
                                        {deleteActionIcon}
                                    </li>
                                )}
                            </FlottedButton>
                        </div>
                    </>
                )
            }
        }),
       
        columnHelper.accessor((row) => row.categoryName, {
            id: 'categoryName',
            header: 'Name',
            cell: (row) => {
                return <p>{row.row.original?.categoryName}</p>
            }
        }),
    ]

    // useEffect while record deleted on last page ////
    useEffect(() => {
        if (currentPage && data?.data?.length == 0) {
            setCurrentPage(1)
        } else {
        }
    }, [currentPage, data?.data])

    // End useEffect ////

    const tableInstance = useReactTable({
        data: data?.data,
        columns: columns,
        state: {
            sorting
        },
        onSortingChange: setSorting,
        getSortedRowModel: getSortedRowModel(),
        getCoreRowModel: getCoreRowModel()
    })

    //Add or Edit User
    const [showAdd, setShowAdd] = useState(false)
    const [addCategoryValue, setAddCategoryValue] = useState('');
    // const [editCategoryId, setEditCategoryId] = useState('');
    // console.log('editCategoryId',)

    // console.log('addCategoryValue', addCategoryValue)

    async function addCatagoryId() {
   
        if(EditDataRef.current) {
            return await requestApi.post(`/faqCategory/add-edit`, {
                categoryName: addCategoryValue,categoryId:EditDataRef.current
        })}
        else
        {
            return await requestApi.post(`/faqCategory/add-edit`, {
                categoryName: addCategoryValue
        })
    }
    }
    
    const mutationAddEdit = useMutation(addCatagoryId, {
        onSuccess: ({data}) => {
            queryClient.invalidateQueries('faqcategorylist')
            EditDataRef.current = null
            queryClient.invalidateQueries(addCategoryValue)
            setAddCategoryValue("")
            setShowAdd(false)   
        },
        onError: (error) => {
            EditDataRef.current = null
            Swal.fire({
                position: 'center',
                icon: 'error',
                title: '',
                text: error?.message
            })
        }
    })

    const handleAddEditCatagory = () =>{
        mutationAddEdit.mutate(addCategoryValue)
    }
    
    // Delete User
    const [showDelete, setShowDelete] = useState(false)
    const [deletedId, setDeletedId] = useState(null)

    async function deletecategoryId(categoryId) {
        return await requestApi.post(`/faqCategory/delete`, {
            categoryId
        })
    }
    const mutationDelete = useMutation(deletecategoryId, {
        onSuccess: ({ data }) => {
            queryClient.invalidateQueries('faqcategorylist')
            setShowDelete(false)
            EditDataRef.current = null
        },
        onError: (error) => {
            EditDataRef.current = null
            Swal.fire({
                position: 'center',
                icon: 'error',
                title: '',
                text: error?.message
            })
        }
    })

    const hanleAddModal = () => {
        setShowAdd(true)
    }

    const hanleDeleteModal = (categoryId) => {
        setShowDelete(true)
        setDeletedId(categoryId)
    }
    const handleDeleteUser = (categoryId) => {
        mutationDelete.mutate(categoryId)
        setShowDelete(false)
    }

    return (
        <>
            <div className="sidebar-content common-page">
                <div className="contentwhole-box details-box">
                    <div className="filter-titlebox">
                        <div className="title-text">
                            <h3>FAQ-Category Management</h3>
                        </div>
                        <div className="filterbox">
                            <div className="searcskills myaccount-page">
                                <div>
                                    <div className="searchstatus-box">
                                        <InputGroup className="mb-3 input-wrapper">
                                            <InputGroup.Text id="basic-addon1">
                                                <SearchIcon />
                                            </InputGroup.Text>
                                            <Form.Control
                                                placeholder="Search"
                                                type="search"
                                                aria-label="Username"
                                                aria-describedby="basic-addon1"
                                                className="icontrol"
                                                {...register(
                                                    'jobOpeningSearch',
                                                    {
                                                        onChange: (e) => {
                                                            handleChange2(e)
                                                        }
                                                    }
                                                )}
                                            />
                                        </InputGroup>
                                        <Button
                                            style={{padding: '0 10px', marginLeft: '20px', width: '100%'}}
                                            className="common-btn save-btn"
                                            onClick={() => hanleAddModal()}
                                        >
                                        + Add Category
                                        </Button>  
                                    </div>
                                </div>
                            </div>      
                        </div>
                    </div>

                    {isLoading ? (
                        <div className="spinner-wrapper">
                            <Spinner
                                animation="border"
                                role="status"
                                className="tdata"
                            >
                                <span className="visually-hidden">
                                    Loading...
                                </span>
                            </Spinner>
                        </div>
                    ) : (
                        <>
                            {' '}
                            {data?.data?.length > 0 ? (
                                <>
                                    <ReactTable tableInstance={tableInstance} />
                                    <div className="paginationbox">
                                        <div className="showingpages">
                                            <span>
                                                Showing{' '}
                                                {(currentPage - 1) * DataLimit +
                                                    1}{' '}
                                                to{' '}
                                                {Math.min(
                                                    currentPage * DataLimit,
                                                    totalJobOpening
                                                )}{' '}
                                                of {totalJobOpening} Categories
                                            </span>
                                        </div>
                                        {totalJobOpening > 10 && <div className="itemsperpage">
                                            <span>Items per page:</span>
                                            <Dropdown
                                                flip="no"
                                                onSelect={handleChange}
                                            >
                                                <Dropdown.Toggle
                                                    variant="success"
                                                    id="dropdown-basic"
                                                >
                                                    {DataLimit}
                                                </Dropdown.Toggle>

                                                <Dropdown.Menu>
                                                    <Dropdown.Item eventKey="10">
                                                        10
                                                    </Dropdown.Item>
                                                    <Dropdown.Item eventKey="20">
                                                        20
                                                    </Dropdown.Item>
                                                    <Dropdown.Item eventKey="30">
                                                        30
                                                    </Dropdown.Item>
                                                </Dropdown.Menu>
                                            </Dropdown>
                                        </div>}
                                        {totalJobOpening > 10 && (
                                            <div className="pagination">
                                                <Pagination
                                                    total={Math.ceil(
                                                        totalJobOpening /
                                                            DataLimit
                                                    )}
                                                    current={currentPage}
                                                    onChangePage={
                                                        handleChangePage
                                                    }
                                                />
                                            </div>
                                        )}
                                    </div>
                                </>
                            ) : (
                                <div className="noresult">
                                    <p>No Result Found</p>
                                </div>
                            )}
                        </>
                    )}
                </div>
            </div>
            <Modal
                className="modalbox showAdd"
                show={showAdd}
                onHide={() => {
                    setAddCategoryValue("")
                    setShowAdd(false)}}
                backdrop="static"
                keyboard={false}
                style={{backdropFilter: 'blur(2px)'}}
            >
                <Modal.Header closeButton><h3>Add Category</h3></Modal.Header>
                <Modal.Body>
                    {
                        console.log(addCategoryValue,"addCategoryValue")
                    }
                    <div>
                        <InputControl
                            name="Category"
                            autoFocus="true"
                            value={addCategoryValue}
                            onChange={(e) => {
                                const inputValue = e.target.value;
                                // Check if the input starts with a space
                                if (inputValue.startsWith(' ')) {
                                    // Handle the validation error (you can show an error message)
                                    // For example: setErrorState(true);
                                } else {
                                    // Update the state with the valid input value
                                    setAddCategoryValue(inputValue);
                                    // Clear the validation error if needed
                                    // For example: setErrorState(false);
                                }
                            }}
                            // onChange={(e) => setAddCategoryValue(e.target.value)}
                        />
                        <div style={{textAlign: 'center'}}>
                            <Button
                                disabled={addCategoryValue === ""}
                                style={{padding: '0 10px'}}
                                className="common-btn save-btn"
                                onClick={() => handleAddEditCatagory()}
                                // onClick={() => console.log("hsfgsjhdkj")}

                            >
                            Submit
                            </Button>
                        </div>
                    </div>
                </Modal.Body>
            </Modal>
            <Modal
                className="modalbox deletemodal"
                show={showDelete}
                onHide={() => setShowDelete(false)}
                backdrop="static"
                keyboard={false}
                style={{backdropFilter: 'blur(2px)'}}
            >
                <Modal.Header closeButton></Modal.Header>
                <Modal.Body>
                    <Form className="formbox">
                        <div className="delete-box">
                            <div className="deleteimg">
                                <DeleteImg />
                            </div>
                            <div className="content">
                                <h4>
                                    Are you sure you want to delete this <br />
                                    FAQ-Category?
                                </h4>
                            </div>
                            <div className="delete-action">
                                <button
                                    className="common-btn yes"
                                    type="button"
                                    onClick={() => handleDeleteUser(deletedId)}
                                >
                                    Yes
                                </button>
                                <button
                                    className="common-btn no"
                                    type="button"
                                    onClick={() => setShowDelete(false)}
                                >
                                    No
                                </button>
                            </div>
                        </div>
                    </Form>
                </Modal.Body>
            </Modal>
        </>
    )
}

export default FaqCategoryManagement;
