import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import Layout from "../Partials/Layout";
import CommonHead from "../UserHeader/CommonHead";

import usersService from "../../services/UsersService";
import { handlePagingFunc } from "../Pagination/HandlePagination";
import PaginatedList from "../Pagination/PaginatedList";
import LoadingSpinner from "../Spinners/LoadingSpinner";
import OthersInterestedTable from "./OthersInterestedTable";

export default function ManageInterestOffer(props) {
    const navigate = useNavigate()
    const apiCall = new usersService()

    let [redirectTime, setRedirectTime] = useState(5)

    let [tab, setTab] = useState("info"); //message STATE FOR SWITCHING BETWEEN TABS

    let [requestStatus, setRequestStatus] = useState({loading: false, status: false, message: '', processType: ''})

    const messageList = {data: [1,2,3,4,5,6]} // TO BE REMOVED AND REPLACE WITH REAL MESSAGE FROM API CALL
    const [currentPage, setCurrentPage] = useState(0);
    const indexOfFirstItem = Number(currentPage);
    const indexOfLastItem = Number(indexOfFirstItem) + Number(process.env.REACT_APP_ITEM_PER_PAGE);
    const currentMessageList = messageList?.data?.slice(indexOfFirstItem, indexOfLastItem);

    const handlePagination = (e) => {
        handlePagingFunc(e, setCurrentPage);
    };

    const [selectTab, setValue] = useState("today");
    const filterHandler = (value) => {
        setValue(value);
    };

    //FUNCTION TO ACCEPT/REJECT OFFER INTEREST
    const interestOfferProcess = ({target:{name}}) => {
        setRequestStatus(prev => ({...prev, loading: true, processType: name}))
        let reqData = { // API PAYLOADS
            proc: name.toUpperCase(),
            client_uid : props.offerDetails?.client_uid,
            offer_code : props.offerDetails?.offer_code,
            offer_uid: props.offerDetails?.offer_uid,
        }
        apiCall.offersInterestProc(reqData).then(res => {
            if(res.status != 200 || res.data.internal_return < 0){
                setRequestStatus({loading: false, status: false, message: 'Unable to complete request', processType: ''})
                return
            }
            let intervalTime = setInterval(() => {  // SETS REDIRECT COUNT DOWN
                setRedirectTime(prev => prev - 1)
            }, 1000);
            setRequestStatus({loading: false, status: true, message: `Offer ${name}ed`, processType: ''})
            setTimeout(()=>{
                navigate('/offer-interest', {replace: true})
                clearInterval(intervalTime)
            },5000)
        }).catch(err => {
            setRequestStatus({loading: false, status: false, message: 'Opps! something went wrong. Try again', processType: ''})
        }).finally(()=>{
            setTimeout(()=>{
                setRequestStatus({loading: false, status: false, message: '', processType: ''})
            },5000)
        })
    }

    useEffect(()=>{
        // run API to get message to replace message array above, add reload variable as dependence array
    },[])
    return (
        <Layout>
            <CommonHead
                commonHeadData={props.commonHeadData}
            />
            <div className="notification-page w-full mb-10">
                <div className="notification-wrapper w-full mb-4">
                    {/* heading */}
                    <div className="sm:flex justify-between items-center mb-3">
                        <div className="mb-3 sm:mb-0">
                            <h1 className="text-26 font-bold text-dark-gray dark:text-white">
                                <span className={`${selectTab === "today" ? "block" : "hidden"}`}>Manage Offer Interest</span>
                            </h1>
                        </div>

                    </div>

                    {/* manage offer section */}
                    <div className="w-full p-4 bg-white dark:bg-dark-white rounded-2xl section-shadow">
                        <div className="my-2 w-full sm:grid gap-5 grid-cols-4">
                            {/* Detail section */}
                            <div className="w-full mb-5 lg:mb-0 col-span-3">
                                <div className="w-full flex justify-start space-x-3 items-center">
                                    <button
                                    type="button"
                                    className="min-w-[45px] h-auto text-[#374557] border border-sky-blue p-1 rounded-full"
                                    onClick={() =>
                                        navigate('/offer-interest', { replace: true })
                                    }
                                    >
                                    <svg
                                        xmlns="http://www.w3.org/2000/svg"
                                        width="35"
                                        height="35"
                                        viewBox="0 0 24 24"
                                        fill="skyblue"
                                    >
                                        <path d="M19 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H19v-2z" />
                                    </svg>
                                    </button>
                                    <h1 className="text-sm lg:text-xl font-bold text-sky-blue dark:text-white tracking-wide">
                                    {props.offerDetails?.offer_code && props.offerDetails.offer_code}
                                    </h1>
                                </div>
                                <h1 className="my-3 text-xl lg:text-2xl font-bold text-dark-gray dark:text-white tracking-wide border">
                                {props.offerDetails?.title}
                                </h1>

                                <div className="w-full">
                                    {/* switch button */}
                                    <div className="my-1 flex items-center border-b border-slate-300">
                                        <button
                                        name="info"
                                        onClick={(e) => setTab(e.target.name)}
                                        className={`p-2 text-lg font-bold text-slate-600 dark:text-white border ${
                                            tab == "info" ? "border-sky-blue" : "border-slate-300"
                                        } tracking-wide transition duration-200`}
                                        >
                                        Info
                                        </button>
                                        <button
                                        name="message"
                                        onClick={(e) => setTab(e.target.name)}
                                        className={`p-2 text-lg font-bold text-slate-600 dark:text-white border ${
                                            tab == "message" ? "border-sky-blue" : "border-slate-300"
                                        }  tracking-wide transition duration-200`}
                                        >
                                        Messages ({messageList.data.length})
                                        </button>
                                    </div>
                                    {/* END OF switch button */}

                                    {/* info tab */}
                                    {tab == 'info' ?
                                    <div className="info-details w-full border-t">
                                        <div className="my-3 flex items-center gap-1">
                                            <span className="w-[200px] text-lg font-bold text-dark-gray dark:text-white tracking-wide">Name</span>
                                            <span className="min-w-[100px] text-sm font-bold text-dark-gray dark:text-white tracking-wide">{props.offerDetails?.client_name}</span>
                                        </div>
                                        <div className="my-3 flex items-center gap-1">
                                            <span className="w-[200px] text-lg font-bold text-dark-gray dark:text-white tracking-wide">Member Since</span>
                                            <span className="min-w-[100px] text-sm font-bold text-dark-gray dark:text-white tracking-wide">{props.offerDetails?.client_added}</span>
                                        </div>
                                        <div className="my-3 flex items-center gap-1">
                                            <span className="w-[200px] text-lg font-bold text-dark-gray dark:text-white tracking-wide">Jobs completed</span>
                                            <span className="min-w-[100px] text-sm font-bold text-dark-gray dark:text-white tracking-wide">{props.offerDetails?.client_jobs_completed ? props.offerDetails?.client_jobs_completed :0}</span>
                                        </div>
                                        <div className="my-0 md:my-3 block md:flex items-center gap-10">
                                            <div className="my-3 md:my-0 flex items-center gap-1">
                                                <span className="w-[200px] text-lg font-bold text-dark-gray dark:text-white tracking-wide">Jobs active</span>
                                                <span className="min-w-[100px] text-sm font-bold text-dark-gray dark:text-white tracking-wide">{props.offerDetails?.client_jobs_active ? props.offerDetails?.client_jobs_active:0}</span>
                                            </div>
                                            <div className="my-3 md:my-0 flex items-center gap-1">
                                                <span className="w-[200px] text-lg font-bold text-dark-gray dark:text-white tracking-wide">Jobs uncompleted</span>
                                                <span className="min-w-[100px] text-sm font-bold text-dark-gray dark:text-white tracking-wide">{props.offerDetails?.client_jobs_missed ? props.offerDetails?.client_jobs_missed:0}</span>
                                            </div>
                                        </div>
                                        <div className="block md:flex items-center gap-10">
                                            <div className="my-3 md:my-0 flex items-center gap-1">
                                                <span className="w-[200px] text-lg font-bold text-dark-gray dark:text-white tracking-wide">% completion</span>
                                                <span className="min-w-[100px] text-sm font-bold text-dark-gray dark:text-white tracking-wide">{props.offerDetails?.client_percent_completion ? props.offerDetails?.client_percent_completion:0}</span>
                                            </div>
                                            <div className="flex items-center gap-1">
                                                <span className="w-[200px] text-lg font-bold text-dark-gray dark:text-white tracking-wide">Pending Offers</span>
                                                <span className="min-w-[100px] text-sm font-bold text-dark-gray dark:text-white tracking-wide">{props.offerDetails?.client_offers_pending ? props.offerDetails?.client_offers_pending:0}</span>
                                            </div>
                                        </div>
                                    </div>
                                    :
                                    <div className="message-details w-full border-t">
                                        <div className="my-0 w-full flex items-center gap-5">
                                            <div className="w-3/4">
                                                <p className="text-base font-bold text-dark-gray dark:text-white tracking-wide">Message to dummy name</p>
                                                <textarea rows={2} autoFocus={true} className="p-2 text-base font-bold text-dark-gray dark:text-white dark:bg-dark-gray border tracking-wide w-full resize-none rounded-md outline-none" />
                                            </div>
                                            <div className="w-1/4 flex flex-col justify-center items-center">
                                                <button
                                                    type="button"
                                                    className="px-2 py-1 h-11 flex justify-center items-center btn-gradient text-base rounded-full text-white"
                                                >
                                                    <span className="text-white">Send</span>
                                                </button>
                                            </div>
                                        </div>
                                        {/* message list */}
                                        <div className="min-h-[100px] max-h-[200px] overflow-y-auto">
                                        {currentMessageList.map((item, index)=>(
                                            <div key={index} className="my-2 w-full flex items-center gap-1">
                                                <p className="text-base font-bold text-dark-gray dark:text-white tracking-wide">2023-04-06-from { }<span className="font-normal">Dummy name</span></p>
                                                <p className="text-base font-bold text-dark-gray dark:text-white tracking-wide">I am testing message</p>
                                            </div>
                                        ))}
                                        </div>

                                        {/* PAGINATION BUTTON */}
                                        <PaginatedList
                                            onClick={handlePagination}
                                            prev={currentPage == 0 ? true : false}
                                            next={
                                                currentPage + Number(process.env.REACT_APP_ITEM_PER_PAGE) >=
                                                messageList?.data?.length
                                                    ? true
                                                    : false
                                            }
                                            data={messageList?.data}
                                            start={indexOfFirstItem}
                                            stop={indexOfLastItem}
                                        />
                                        {/* END OF PAGINATION BUTTON */}
                                    </div>
                                    }
                                </div>
                            </div>
                            {/* END OF Detail section */}

                            {/* BUTTON section */}
                            <div className="p-4 w-full min-h-full bg-sky-100 dark:bg-dark-gray col-span-1">
                                <div className="w-full h-full">
                                    <div className="mt-0 sm:mt-10 flex sm:flex-col justify-center items-center gap-10">
                                        {requestStatus.loading && requestStatus.processType == 'accept' ?
                                            <LoadingSpinner color='sky-blue' size='10' />
                                        :    
                                            <button
                                                type="button"
                                                name='accept'
                                                disabled={requestStatus.loading}
                                                onClick={interestOfferProcess}
                                                className="px-2 py-1 h-11 flex justify-center items-center btn-gradient text-base rounded-full text-white"
                                            >
                                            Accept
                                            </button>
                                        }

                                        {requestStatus.loading && requestStatus.processType == 'reject' ?
                                            <LoadingSpinner color='sky-blue' size='10' />
                                        :
                                            <button
                                                type="button"
                                                name='reject'
                                                disabled={requestStatus.loading}
                                                onClick={interestOfferProcess}
                                                className="px-2 py-1 h-11 flex justify-center items-center border-gradient text-base rounded-full text-black"
                                            >
                                            Reject
                                            </button>
                                        }
                                    </div>

                                    {/* ERROR DISPLAY */}
                                    <div className="w-full">
                                    {/* error or success display */}
                                    {requestStatus.message != "" && requestStatus.processType != 'sendmeassge' &&
                                        (!requestStatus.status ? (
                                        <div
                                            className={`relative p-4 my-4 text-[#912741] bg-[#fcd9e2] border-[#fbc6d3] mb-4 rounded-[0.475rem] text-md font-light leading-[19.5px] text-[13px]`}
                                        >
                                            {requestStatus.message}
                                        </div>
                                        ) : (
                                        requestStatus.status && (
                                            <div
                                            className={`relative p-4 my-4 text-green-700 bg-slate-200 border-slate-800 mb-4 rounded-[0.475rem] text-md font-light leading-[19.5px] text-[13px]`}
                                            >
                                            {`${requestStatus.message} redirecting.... ${redirectTime}sec`}
                                            </div>
                                        )
                                        ))}
                                    </div>
                                    {/* End of error or success display */}
                                </div>
                            </div>
                            {/* END of BUTTON section */}
                        </div>
                    </div>
                    {/* END OF manage offer section */}
                </div>

                <div className="w-full overflow-x-auto">
                    {/* heading */}
                    <div className="sm:flex justify-between items-center mb-3">
                        <div className="mb-3 sm:mb-0">
                            <h1 className="text-26 font-bold text-dark-gray dark:text-white">
                                <span className={`${selectTab === "today" ? "block" : "hidden"}`}>Others interested in this Task</span>
                            </h1>
                        </div>
                    </div>
                    <OthersInterestedTable othersInterestedList={props.othersInterestedList} />
                </div>
            </div>
        </Layout>
    );
}
