import React, { useCallback, useRef, useState } from 'react'
import {
    createColumnHelper,
    getCoreRowModel,
    useReactTable,
    getSortedRowModel
} from '@tanstack/react-table'
import * as yup from 'yup'
import { yupResolver } from '@hookform/resolvers/yup'
import { useMutation, useQuery, useQueryClient } from 'react-query'
import { Button, Col, Dropdown, Form, InputGroup, Modal, Row } from 'react-bootstrap'
import { Link, 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, getFormData } from '../../functions/common'
import Swal from 'sweetalert2'
import { ReactComponent as DeleteImg } from '../../assets/images/redbin.svg'
import { ReactComponent as SelectImg } from '../../assets/images/selectimg.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'
import ClassicEditor from '@ckeditor/ckeditor5-build-classic'
import ckeditor, { CKEditor } from '@ckeditor/ckeditor5-react'
import DefaultThumb from '../../assets/images/defaultThumb.png'
const Testimonial = () => {

    const compliancevalidation = yup.object({
        name: yup.string().max(25,"Maximum charactor is 25").nullable().trim().required('Please enter Name.'),
        position: yup.string().max(25,"Maximum charactor is 25").nullable().trim().required('Please enter Position.'),
        description: yup
            .string().nullable()
            .trim()
            .required('Please enter job description'),
        type: yup.string().required('Please select Showing'),
    })


    const {
        control,
        register,
        watch,
        clearErrors,
        handleSubmit,
        reset,
        setError,
        setValue,
        formState: { errors }
    } = useForm({
        resolver: yupResolver(compliancevalidation),
        shouldUnregister: true,
      defaultValues:{
        type:"candidate"
      }
    })
    const navigate = useNavigate()
    const[EditID,setEditID] =useState("")
    const [ckeditordata, setckeditordata] = useState('')
    const [toggle, setToggle] = useState(null)
    const queryClient = useQueryClient()
    const [DataLimit, setDataLimit] = useState(10)
    const [editValueID, setEditValueID] = useState('')
    const [currentPage, setCurrentPage] = useState(1)
    const [imageErr,setimageErr] = useState('')
    const EditDataRef = useRef(null)
    const [userFilterText, setuserFilterText] = useState('')
    const [showOption, setShowOption] = useState('candidate')
    const handleChange2 = (e) => {
        setCurrentPage(1)
        const getData = setTimeout(() => {
            setuserFilterText(e.target.value)
        }, 1000)
        clearInterval()
    }

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


    function edittestimonial(testimonialitems) {
        setShowAdd(true)
        setEditID(testimonialitems.testimonialId)
        setImageUrl(testimonialitems.testimonialPhoto)
        for (const key in testimonialitems) {

            setValue(key,testimonialitems[key])
        }
    }

    /////status filter////
    const [statusControl, setStatusControl] = useState('')
    const handleChangeStatus = (eventKey) => {
        setCurrentPage(1)
        setStatusControl(eventKey)
    }


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

    function UserList({ queryKey }) {
        return requestApi
            .post(
                `/testimonial/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: [
            'testimoniallist',
            currentPage,
            DataLimit,
            userFilterText,
            sorting[0],
            statusControl
        ],
        queryFn: UserList
        // select: () => {
        //     return {
        //         data: null
        //     }
        // }
    })

    //View Data
    const [showViewModal, setShowViewModal] = useState(false)
    const [viewData, setViewData] = useState('');

    const viewTestimonialData = (ViewData) => {
        setViewData(ViewData)
        setShowViewModal(true)
    }


    let totalTestimonials = 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?.testimonialId
                                            ? null
                                            : row.row.original?.testimonialId
                                    )
                                }}
                                isTrue={
                                    row.row.original?.testimonialId === toggle
                                }
                            >
                                {row.row.original.status === 3
                                    ? ''
                                    : <li
                                        className=" i1 icon"
                                        onClick={() =>
                                        viewTestimonialData(
                                        row.row.original
                                        )
                                        }
                                    >
                                        {viewIcon}
                                    </li>
                                }
                                <li
                                    className=" i1 icon"
                                    onClick={() => {
                                        edittestimonial(row.row.original)
                                    }}
                                >
                                    {editactionIcon}
                                </li>

                                {row.row.original.status === 3 ? (
                                    ''
                                ) : (
                                    <li
                                        className=" i1 icon"
                                        onClick={() =>
                                            hanleDeleteModal(
                                                row.row.original?.testimonialId
                                            )
                                        }
                                    >
                                        {deleteActionIcon}
                                    </li>
                                )}
                            </FlottedButton>
                        </div>
                    </>
                )
            }
        }),
        columnHelper.accessor((row) => row.testimonialPhoto, {
            id: 'testimonialPhoto',
            header: 'Photo',
            enableSorting:false,
            cell: (row) => {
                return <img src={row.row.original?.testimonialPhoto} alt="fgf"/>
            }
        }),
        columnHelper.accessor((row) => row.name, {
            id: 'name',
            header: 'Name',
            cell: (row) => {
                return <p>{row.row.original?.name}</p>
            }
        }),
        columnHelper.accessor((row) => row.position, {
            id: 'position',
            header: 'Position',
            cell: (row) => {
                return <p>{row.row.original?.position}</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 testimonialId(payload ) {
       
            return await requestApi.post(`/testimonial/add-edit`, 
               payload,
            )
            .then((res) => {
                return res.data
            })
        
    }

    const mutationAddEdit = useMutation(testimonialId, {
        onSuccess: ({ data }) => {
            reset()
            queryClient.invalidateQueries('testimoniallist')
            // setValue("name","4545454")
            setShowAdd(false)
            // setValue("testimonialId",null)
            
        },
        onError: (error) => {
            EditDataRef.current = null
            Swal.fire({
                position: 'center',
                icon: 'error',
                title: '',
                text: error?.message
            })
        }
    })


    const uploadImage = useRef(null)
    const [imageUrl, setImageUrl] = useState(null)

    const handleFileUpload = (e) => {  
        if (
            e.target.files[0].type === 'image/jpg' ||
            e.target.files[0].type === 'image/jpeg' ||
            e.target.files[0].type === 'image/png'
        ) {
            setValue('testimonialPhoto', e.target.files[0])
            setImageUrl(URL.createObjectURL(e.target.files[0]))   
            setimageErr('')
        } else {
            setimageErr('Please select .jpeg, .jpg or .png file formate.')
        }
    }

    const handleAddEditCompliance = () => {
        mutationAddEdit.mutate(addCategoryValue)
        setShowAdd(false)
    }

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

    async function deletecategoryId(testimonialId) {
        return await requestApi.post(`/testimonial/delete`, {
            testimonialId
        })
    }
    const mutationDelete = useMutation(deletecategoryId, {
        onSuccess: ({ data }) => {
            queryClient.invalidateQueries('testimoniallist')
            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 = (testimonialId) => {
        setShowDelete(true)
        setDeletedId(testimonialId)
    }
    const handleDeleteUser = (testimonialId) => {
        mutationDelete.mutate(testimonialId)
        setShowDelete(false)
    }

    const handleCompliance= (data)=>{
        const {testimonialId,...rest}=data
       
     if (testimonialId) {
        mutationAddEdit.mutate(getFormData({testimonialId,...rest}))
        setEditID(null)
        
     }else{
        mutationAddEdit.mutate(getFormData(rest))  
    }
    }

    return (
        <>
            <div className="sidebar-content common-page">
                <div className="contentwhole-box details-box">
                    <div className="filter-titlebox">
                        <div className="title-text">
                            <h3>Testimonial</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 Testimonial
                                        </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,
                                                    totalTestimonials
                                                )}{' '}
                                                of {totalTestimonials}{' '}
                                                Testimonials
                                            </span>
                                        </div>
                                        {totalTestimonials > 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>
                                        )}
                                        {totalTestimonials > 10 && (
                                            <div className="pagination">
                                                <Pagination
                                                    total={Math.ceil(
                                                        totalTestimonials /
                                                            DataLimit
                                                    )}
                                                    current={currentPage}
                                                    onChangePage={
                                                        handleChangePage
                                                    }
                                                />
                                            </div>
                                        )}
                                    </div>
                                </>
                            ) : (
                                <div className="noresult">
                                    <p>No Result Found</p>
                                </div>
                            )}
                        </>
                    )}
                </div>
            </div>
            <Modal
                size="lg"
                style={{ backdropFilter: 'blur(2px)' }}
                className="modalbox showAdd testimonial-modal"
                show={showAdd}
                onHide={() => {
                    setImageUrl('')
                    setValue('testimonialPhoto', '')
                    setAddCategoryValue('')
                    setShowAdd(false)
                    setValue('testimonialId', null)
                    setEditID('')
                }}
                backdrop="static"
                keyboard={false}
            >
                <Modal.Header closeButton>
                    {/* <h3>Add Testimonial</h3> */}
                    <h3>{EditID ? 'Edit Testimonial' : 'Add Testimonial'}</h3>
                </Modal.Header>
                <Modal.Body>
                    <div>
                        <Form onSubmit={handleSubmit(handleCompliance)}>
                            <div className="col-12">
                                <div className="profile-image">
                                    {imageUrl ? (
                                        <img src={imageUrl} alt="" />
                                    ) : (
                                        <img src={DefaultThumb} alt="" />
                                    )}
                                    <div
                                        className="selectimg"
                                        onClick={() =>
                                            uploadImage.current.click()
                                        }
                                    >
                                        <input
                                            type="file"
                                            ref={(event) => {
                                                register('testimonialPhoto')
                                                uploadImage.current = event
                                            }}
                                            accept=".jpg,.png,.jpeg"
                                            style={{ display: 'none' }}
                                            onChange={handleFileUpload}
                                        />
                                        <SelectImg />
                                    </div>
                                </div>
                                {!!imageErr && (
                                    <span className="error-message">
                                        {imageErr}
                                    </span>
                                )}
                            </div>

                            <div className="wrap">
                                <InputControl
                                    label="Name"
                                    name="name"
                                    register={register}
                                    autoFocus="true"
                                    error={errors?.name?.message}
                                />
                                <InputControl
                                    label="Position"
                                    name="position"
                                    register={register}
                                    autoFocus="true"
                                    error={errors?.position?.message}
                                />

                                {/* <Dropdown flip="no" 
                                onSelect={handleChange4}
                                >
                                    <Dropdown.Toggle
                                        variant="success"
                                        id="dropdown-basic"
                                    >
                                        {showOption}
                                    </Dropdown.Toggle>

                                    <Dropdown.Menu>
                                        <Dropdown.Item eventKey="client">
                                           Client
                                        </Dropdown.Item>
                                        
                                        <Dropdown.Item eventKey="candidate">
                                           Candidate
                                        </Dropdown.Item>
                                    </Dropdown.Menu>
                                </Dropdown> */}

                                <div className="mb-3 input-wrapper">
                                    <Form.Label className="lcontrol">
                                        Showing At
                                    </Form.Label>
                                    <DropDownControl
                                        name="type"
                                        control={control}
                                        options={['candidate', 'client']}
                                        register={register}
                                        error={errors.type?.message}
                                    />
                                </div>
                            </div>
                            <div>
                                <div class="input-wrapper">
                                    <h3 class="lcontrol">Description</h3>
                                </div>
                                <div className="jobdesbox">
                                    <div className="createnew-box">
                                        <Controller
                                            control={control && control}
                                            name={'description'}
                                            render={({
                                                field: {
                                                    value,
                                                    onChange: ckEditoronchange
                                                }
                                            }) => (
                                                <CKEditor
                                                    data={value ?? ''}
                                                    editor={ClassicEditor}
                                                    config={{
                                                        removePlugins: [
                                                            'EasyImage',
                                                            'ImageUpload',
                                                            'MediaEmbed'
                                                        ],
                                                        link: {
                                                            addTargetToExternalLinks: true
                                                        }
                                                    }}
                                                    onReady={(editor) =>
                                                        // data?.data?.jobDescription
                                                        console.log(
                                                            editor,
                                                            'hello'
                                                        )
                                                    }
                                                    onChange={(
                                                        event,
                                                        editor
                                                    ) => {
                                                        const data =
                                                            editor.getData()
                                                        ckEditoronchange(data)
                                                    }}
                                                />
                                            )}
                                        />
                                        <span className="error-message">
                                            {errors.description?.message}
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <div
                                style={{
                                    textAlign: 'center',
                                    marginTop: '20px'
                                }}
                            >
                                <Button
                                    type="submit"
                                    style={{ padding: '0 10px' }}
                                    className="common-btn save-btn"
                                    // onClick={() => handleAddEditCopliance()}
                                    // onClick={() => console.log("hsfgsjhdkj")}
                                >
                                    Submit
                                </Button>
                            </div>
                        </Form>
                    </div>
                </Modal.Body>
            </Modal>

            <Modal
                size="lg view-modal-testi"
                style={{ backdropFilter: 'blur(2px)' }}
                className="modalbox view testimonial-modal"
                show={showViewModal}
                onHide={() => {
                    setShowViewModal(false)
                    setImageUrl('')
                    setValue('testimonialPhoto', '')
                    setAddCategoryValue('')
                    setShowAdd(false)
                    setValue('testimonialId', null)
                    setEditID('')
                }}
                backdrop="static"
                keyboard={false}
            >
                <Modal.Header closeButton>
                    {/* <h3>Add Testimonial</h3> */}
                    <h3>View Testimonial</h3>
                </Modal.Header>
                <Modal.Body>
                    <div className="col-12">
                        <div className="profile-image">
                            <img
                                src={viewData?.testimonialPhoto}
                                height="75px"
                                width="75px"
                                style={{ width: '170px', height: '170px' }}
                            />
                        </div>
                        <div className="testimonial-data">
                            <div className="modal-wrap">
                                <h4>Testimonial Name :</h4>
                                <p style={{ fontSize: '16px' }}>
                                    {viewData?.name}
                                </p>
                            </div>
                            <div className="modal-wrap">
                                <h4>Position Name :</h4>
                                <p style={{ fontSize: '16px' }}>
                                    {viewData?.position}
                                </p>
                            </div>
                        </div>

                        <div style={{ marginTop: '10px' }}>
                            <h4>Description :</h4>
                            <div className="testmonial-description">
                                <div
                                    dangerouslySetInnerHTML={{
                                        __html: viewData?.description
                                    }}
                                ></div>
                            </div>
                        </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 />
                                    Testimonial?
                                </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 Testimonial
