import React, { useCallback, 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 { Link, NavLink, useNavigate, useParams } from 'react-router-dom'
import { Controller, useForm } from 'react-hook-form'
import ReactTable from '../../components/ReactTable'
import Pagination from '../../components/Pagination'
import requestApi from '../../utils/request'
import { formatDateToMonthShortwithFormate } from '../../functions/common'
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, viewjobopening, creatnewopening } 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'

const JobOpeningManagement = () => {
    const navigate = useNavigate()
    const [toggle, setToggle] = useState(null)
    const queryClient = useQueryClient()
    const [DataLimit, setDataLimit] = useState(10)
    const [currentPage, setCurrentPage] = useState(1)
    // const [TotalPagies, setTotalPagies] = useState(1)
    const [userFilterText, setuserFilterText] = useState('')
    const handleChange2 = (e) => {
        setCurrentPage(1)
        const getData = setTimeout(() => {
            setuserFilterText(e.target.value)
        }, 1000)
        clearInterval()
    }

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

    function viewjobopeningData(id) {
        navigate(`${viewjobopening}/${id}`)
    }

    function editjobopening(jobopeningid) {
        navigate(`${creatnewopening}/${jobopeningid}`)
    }

    /////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(
                `/job-opening/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: [
            'jobOpeninglist',
            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?.jobOpeningId
                                            ? null
                                            : row.row.original?.jobOpeningId
                                    )
                                }}
                                isTrue={
                                    row.row.original?.jobOpeningId === toggle
                                }
                            >
                                {row.row.original.status === 3 ? (
                                    ''
                                ) : (
                                    <li
                                        className=" i1 icon"
                                        onClick={() =>
                                            viewjobopeningData(
                                                row.row.original?.jobOpeningId
                                            )
                                        }
                                    >
                                        {viewIcon}
                                    </li>
                                )}
                                <li
                                        className=" i1 icon"
                                        onClick={() =>
                                            editjobopening(
                                                row.row.original?.jobOpeningId
                                            )
                                        }
                                    >
                                        {editactionIcon}
                                    </li>
                                {/* <Link
                                    to={`/createnewopening/${row?.row?.original?.userId}`}
                                >
                                    <button
                                        className="action-btn"
                                        onClick={() =>
                                            editjobopening(
                                                row.row.original?.jobOpeningId
                                            )
                                        }
                                    >
                                        <span>
                                            <Edit />
                                        </span>
                                    </button>
                                </Link> */}
                                {row.row.original.status === 3 ? (
                                    ''
                                ) : (
                                    <li
                                        className=" i1 icon"
                                        onClick={() =>
                                            hanleDeleteModal(
                                                row.row.original?.jobOpeningId
                                            )
                                        }
                                    >
                                        {deleteActionIcon}
                                    </li>
                                )}
                            </FlottedButton>
                        </div>
                    </>
                )
            }
        }),
        // columnHelper.accessor((row) => row.companyProfile, {
        //     id: 'companyProfile',
        //     header: 'Company',
        //     cell: (row) => {
        //         return <img src={row.row.original?.companyProfile} alt="" />
        //     }
        // }),

        columnHelper.accessor((row) => row.jobTitle, {
            id: 'jobTitle',
            header: 'Job Title',
            cell: (row) => {
                return <p>{row.row.original?.jobTitle}</p>
            }
        }),
        columnHelper.accessor((row) => row.companyName, {
            id: 'categoryName',
            header: 'Category Name',
            cell: (row) => {
                return (
                    // <Link
                    //     to={`${employerview}/${row.row.original?.employerId}`}
                    // >
                        <p>{row.row.original?.categoryName}</p>
                    // </Link>
                )
            }
        }),
        columnHelper.accessor((row) => row.location, {
            id: 'location',
            header: 'Location',
            cell: (row) => {
                return <p>{row.row.original?.location?.label}</p>
            }
        }),
        columnHelper.accessor((row) => row.shiftType, {
            id: 'shiftType',
            header: 'shift Type',
            cell: (row) => {
                return (
                    <p>
                        {row.row.original?.shiftType}
                    </p>
                )
            }
        }),
        columnHelper.accessor((row) => row.shiftType, {
            id: 'jobType',
            header: 'job Type',
            cell: (row) => {
                return (
                    <p>
                        {row.row.original?.jobType}
                    </p>
                )
            }
        }),
        columnHelper.accessor((row) => row.salary, {
            id: 'salary',
            header: 'Salary (£)',
            cell: (row) => {
                return <p>{row.row.original?.salary}</p>
            }
        }),
        columnHelper.accessor((row) => row.salaryType, {
            id: 'salaryType',
            header: 'Salary Type',
            cell: (row) => {
                return <p>{row.row.original?.salaryType}</p>
            }
        }),

        columnHelper.accessor((row) => row.jobRole, {
            id: 'jobRole',
            header: 'Job Role',
            cell: (row) => {
                return <p>{row.row.original?.jobRole}</p>
            }
        }),
        // columnHelper.accessor((row) => row.summary, {
        //     id: 'summary',
        //     header: 'Summary',
        //     cell: (row) => {
        //         return <p>{row.row.original?.summary}</p>
        //     }
        // }),
        // columnHelper.accessor((row) => row.mainDuty, {
        //     id: 'mainDuty',
        //     header: 'Main Duty',
        //     cell: (row) => {
        //         return <div dangerouslySetInnerHTML={{__html:row.row.original?.mainDuty}}></div>
        //     }
        // }),
        // columnHelper.accessor((row) => row.aboutUs, {
        //     id: 'aboutUs',
        //     header: 'About Us',
        //     cell: (row) => {
        //         return <p>{row.row.original?.aboutUs}</p>
        //     }
        // }),
        // columnHelper.accessor((row) => row.description, {
        //     id: 'description',
        //     header: 'Description',
        //     cell: (row) => {
        //         return <p>{row.row.original?.description}</p>
        //     }
        // }),
        // columnHelper.accessor((row) => row.lookingFor, {
        //     id: 'lookingFor',
        //     header: 'Looking For',
        //     cell: (row) => {
        //         return <div dangerouslySetInnerHTML={{__html:row.row.original.lookingFor}}></div>
        //     }
        // }),
        // columnHelper.accessor((row) => row.additionalInfo, {
        //     id: 'additionalInfo',
        //     header: 'Additional Info',
        //     cell: (row) => {
        //         return <p>{row.row.original?.additionalInfo}</p>
        //     }
        // }),

        // columnHelper.accessor((row) => row.jobStatus, {
        //     id: 'jobStatus',
        //     header: 'Job Status',
        //     cell: (row) => {
        //         let flag = row.row.original.jobStatus
        //         return (
        //             <p
        //                 className={`labels ${
        //                     flag === 'Active'
        //                         ? 'active'
        //                         : flag === 'Inactive'
        //                         ? 'inactive'
        //                         : flag === 'Archived'
        //                         ? 'archived'
        //                         : ''
        //                 }`}
        //             >
        //                 {/* {flag === 1 ? 'Active' :flag === 2 ? 'Inactive':flag === 3 ? 'Archived' : ''} */}
        //                 {row.row.original.jobStatus}
        //             </p>
        //         )
        //     }
        // })

        // columnHelper.accessor((row) => row.status, {
        //     id: 'status',
        //     header: 'Status',
        //     cell: (row) => {
        //         let flag = row.row.original.status
        //         return (
        //             <p
        //                 className={`labels ${
        //                     flag === 0 || flag === 1
        //                         ? 'active'
        //                         : // : flag === 'Inactive'
        //                         // ? 'inactive'
        //                         flag === 3
        //                         ? 'deleted'
        //                         : ''
        //                 }`}
        //             >
        //                 {flag === 0 || flag === 1
        //                     ? 'Active'
        //                     : flag === 3
        //                     ? 'Deleted'
        //                     : ''}
        //                 {/* {row.row.original.status} */}
        //             </p>
        //         )
        //     }
        // })

        // columnHelper.display({
        //     id: 'actions',
        //     header: 'Action',
        //     cell: (row) => {
        //         return (
        //             <>
        //                 <div className="actionbox">
        //                     {row.row.original.status === 3 ? (
        //                         ''
        //                     ) : (
        //                         <button
        //                             className="action-btn"
        //                             onClick={() =>
        //                                 editjobopeningData(
        //                                     row.row.original?.jobOpeningId
        //                                 )
        //                             }
        //                         >
        //                             {viewIcon}
        //                         </button>
        //                     )}
        //                     {/* <Link
        //                     to={`/createnewopening/${row?.row?.original?.userId}`}
        //                 > */}
        //                     {/* <button
        //                     className="action-btn"
        //                     // onClick={() =>
        //                     //     editjobopening(
        //                     //         row.row.original?.jobOpeningId
        //                     //     )
        //                     // }
        //                 >
        //                     <span>
        //                         <Edit />
        //                     </span>
        //                 </button> */}
        //                     {/* </Link> */}
        //                     {row.row.original.status === 3 ? (
        //                         ''
        //                     ) : (
        //                         <button
        //                             className="action-btn"
        //                             onClick={() =>
        //                                 hanleDeleteModal(
        //                                     row.row.original?.jobOpeningId
        //                                 )
        //                             }
        //                         >
        //                             {deleteActionIcon}
        //                         </button>
        //                     )}
        //                 </div>
        //             </>
        //         )
        //     }
        // })
    ]

    // 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()
    })

    // Delete User

    const [showDelete, setShowDelete] = useState(false)
    const [deletedId, setDeletedId] = useState(null)

    async function deleteJobOpeningId(jobOpeningId) {
        return await requestApi.post(`/job-opening/delete`, {
            jobOpeningId
        })
    }
    const mutationDelete = useMutation(deleteJobOpeningId, {
        onSuccess: ({ data }) => {
            queryClient.invalidateQueries('jobOpeninglist')
            setShowDelete(false)
        },
        onError: (error) => {
            Swal.fire({
                position: 'center',
                icon: 'error',
                title: '',
                text: error?.message
            })
        }
    })

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

    return (
        <>
            <div className="sidebar-content common-page">
                <div className="contentwhole-box">
                    <div className="filter-titlebox">
                        <div className="title-text">
                            <h3>Manage Job Openings</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>
                                        <NavLink
                                            to={creatnewopening}
                                                className="common-btn save-btn"
                                                style={{padding: '14px', marginLeft: '15px', width: '100%'}}
                                                state="Create New Opening"
                                            >
                                            + Create New Opening
                                        </NavLink>
                                        {/* <div className="status-dropdown">
                                            <Dropdown
                                                placeholder="Status"
                                                onSelect={handleChangeStatus}
                                            >
                                                <Dropdown.Toggle
                                                    variant="success"
                                                    id="dropdown-basic"
                                                >
                                                    {!!statusControl
                                                        ? statusControl
                                                        : 'Job Status'}
                                                </Dropdown.Toggle>

                                                <Dropdown.Menu>
                                                    <Dropdown.Item eventKey="">
                                                        Job Status
                                                    </Dropdown.Item>
                                                    <Dropdown.Item eventKey="Active">
                                                        Active
                                                    </Dropdown.Item>
                                                    <Dropdown.Item eventKey="Inactive">
                                                        Inactive
                                                    </Dropdown.Item>
                                                    <Dropdown.Item eventKey="Archived">
                                                        Archived
                                                    </Dropdown.Item>
                                                </Dropdown.Menu>
                                            </Dropdown>
                                        </div> */}
                                    </div>
                                </div>
                            </div>

                            {/* dashboard drop down */}

                            {/* <div className="title-text">
                        <h5>Job Status</h5>
                        <div className="chartlist">
                            <Dropdown
                                className="week-dropdown"
                                flip="no"
                                onSelect={handleChangeStatus}
                            >
                                <Dropdown.Toggle id="dropdown-basic">
                                    
                                    {statusControl}
                                </Dropdown.Toggle>

                                <Dropdown.Menu className="dropdown-content">
                                    <Dropdown.Item eventKey="Active">
                                        Active
                                    </Dropdown.Item>
                                    <Dropdown.Item eventKey="Inactive">
                                        Inactive
                                    </Dropdown.Item>
                                    <Dropdown.Item eventKey="Archived">
                                        Archived
                                    </Dropdown.Item>
                                </Dropdown.Menu>
                            </Dropdown>
                        </div>
                    </div> */}
                            {/* end dropdown */}

                            {/* </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} Openings
                                            </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 deletemodal"
                show={showDelete}
                onHide={() => setShowDelete(false)}
                backdrop="static"
                keyboard={false}
            >
                <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 />
                                    Job Opening?
                                </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 JobOpeningManagement
