import React, { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import Layout from "../Partials/Layout";
import { useNavigate } from "react-router-dom";
import ActiveJobMessage from "./ActiveJobMessage";
import LoadingSpinner from "../Spinners/LoadingSpinner";

import usersService from "../../services/UsersService";

function ActiveJobs(props) {
  const ApiCall = new usersService()

  let { userDetails } = useSelector((state) => state.userDetails);
  let navigate = useNavigate()

  let [messageToSend, setMessageToSend] = useState('') // State to hold the value of message to be sent

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

  // FUNCTION TO HANDLE MESSAGE CHANGE
  const handleMessageChange = ({target:{value}}) => {
    setMessageToSend(value)
  }

  // FUNCTION TO SEND TASK MESSAGE
  const sendTaskMessage = () => {
    let reqData={message: messageToSend, msg_type: 'TEXT', contract:props.details.contract}
    if(!reqData.message){
      setRequestStatus({loading: false, status: false, message: 'Message is empty'})
      return setTimeout(()=>{
        setRequestStatus({loading: false, status: false, message: ''})
      }, 5000)
    }
    setRequestStatus({loading: true, status: false, message: ''})
    ApiCall.sendTaskMessage(reqData).then((res)=>{
      if(res.status != 200 || res.data.internal_return < 0){
        setRequestStatus({loading: false, status: false, message: 'Message could not be sent, try again later'})
        return
      }
      setRequestStatus({loading: false, status: true, message: 'Message Sent Successfully'})
      props.reloadActiveJobList(prev => !prev) // MAKES ACTIVE JOB MESSAGE LIST TO RELOAD
      setMessageToSend('') // SENDS MESSAGE TO SEND BACK TO EMPTY STRINGS
    }).catch(error => {
      setRequestStatus({loading: false, status: false, message: 'Opps! something went wrong'})
    }).finally(()=>{
      setTimeout(()=>{
        setRequestStatus({loading: false, status: false, message: ''})
      }, 5000)
    })
  }

  return (
    <Layout>

        <div className="p-4 lg:flex justify-between items-start space-y-4 lg:space-x-4 lg:space-y-0 rounded-lg shadow-lg bg-slate-100">
          <div className="w-full lg:w-1/2">
            <div className="py-[20px] bg-white px-4 rounded-md shadow-md">
              {/* back btn and title */}
              <div className="w-full flex justify-start space-x-3 items-center">
                <button
                  type="button"
                  className="text-[#374557] border border-sky-blue p-1 rounded-full"
                  onClick={() => navigate('/my-active-jobs', {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-lg font-bold text-dark-gray dark:text-white tracking-wide">
                  {props.details?.title && props.details.title}
                </h1>
              </div>
              {/* END of back btn and title */}

              <div className="mt-2 w-full lg:flex lg:justify-between lg:items-center lg:space-x-2">
                <div className="my-2 lg:my-0">
                  <p className="text-base text-slate-700 dark:text-black">
                    {props.details?.contract && props.details.contract}
                  </p>
                  <p className="text-base text-slate-700 dark:text-black">
                    <span className="font-semibold">Description: </span>
                    {props.details?.description && props.details.description}
                  </p>
                  <p className="text-base text-sky-blue">Delivery Detail</p>
                </div>
                <div className="">
                  <p className="text-base text-sky-blue">
                    {userDetails.firstname && userDetails.firstname}
                  </p>
                  <p className="text-base text-slate-700 dark:text-black">
                    <span className="font-semibold">Due: </span>
                    {props.details?.delivery_date &&
                      props.details.delivery_date.split(" ")[0]}
                  </p>
                  <p className="text-base text-slate-700 dark:text-black">
                    {props.details?.delivery_date &&
                      props.details.delivery_date.split(" ")[1]}
                  </p>
                  <p className="text-base text-slate-700 dark:text-black">
                    {props.details?.timeline_days && props.details.timeline_days} day(s)
                  </p>
                </div>
              </div>
            </div>

            <div className="mt-5 bg-white p-4 rounded-md shadow-md">
              <div className="">
              <p className="relative py-2 my-2 text-lg font-bold text-slate-600 dark:text-black border-b-2 border-slate-300 tracking-wide after:absolute after:-bottom-0.5 after:content-[''] after:w-[100px] after:h-[2px] after:bg-sky-blue after:left-0">Message(s)</p>
                <textarea
                  className="p-4 w-full text-base text-slate-600 border-y border-slate-300 outline-none"
                  rows="10"
                  style={{ resize: "none" }}
                  name='message'
                  onChange={handleMessageChange}
                  value={messageToSend}
                />
              </div>

              {/* ERROR DISPLAY AND SUBMIT BUTTON */}
              <div className="w-full">
                {/* error or success display */}
                {requestStatus.message != "" &&
                  (!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}
                      </div>
                    )
                  ))}
                </div>
                {/* End of error or success display */}

              {/* Buttons Sections */}
              <div className="py-2 mb-8 sm:flex sm:justify-center sm:items-center">
                <div className="w-full sm:w-2/4 mb-5 sm:mb-0">
                  <button
                    onClick={()=>{console.log('working')}}
                    type="button"
                    className="btn-gradient text-base tracking-wide px-4 py-2 rounded-md flex justify-center items-center"
                  >
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill='white'>
                      <path d="M12 2L2 12h3v8h14v-8h3L12 2zm0 16v-6h-2v6H7l5-5 5 5h-3z"/>
                    </svg>

                    <span className="text-white">Upload Files</span>
                  </button>
                </div>

                <div className="w-full sm:w-2/4 flex justify-between items-center space-x-2">
                  <button
                      type="button"
                      className="bg-red-600 text-base text-white tracking-wide px-4 py-2 rounded-md hover:opacity-90"
                  >
                      <span className="text-white">Clear</span>
                  </button>
                  <button
                    onClick={sendTaskMessage}
                      type="button"
                      className="btn-gradient text-base text-white tracking-wide px-4 py-2 rounded-md"
                  >
                      {requestStatus.loading ? 
                      <LoadingSpinner size='6' color='sky-blue' />
                      :
                      <span className="text-white">Send</span>
                      }
                  </button>
                </div>

              </div>
              {/* end of Buttons Sections  */}
            </div>
          </div>

          {/* ACTION SECTION */}
          <div className="w-full lg:w-1/2 h-full">
            <div className="py-[20px] bg-white px-4 rounded-md shadow-md">
              <h1 className="text-lg font-bold text-dark-gray dark:text-white tracking-wide">Actions</h1>

              <p className="my-3 py-1 text-base">
                Waiting for the completion message from the client before you can approve.
              </p>
            </div>

            <div className="mt-5 bg-white p-4 rounded-md shadow-md">
              <div className="">
                <p className="text-lg font-bold text-dark-gray dark:text-black tracking-wide">Message</p>
                {props.activeJobMesList.loading ?
                <LoadingSpinner size='16' color='sky-blue' />
                :
                <ActiveJobMessage activeJobMesList={props.activeJobMesList} />
                }
              </div>
            </div>

          </div>
        </div>

    </Layout>
  );
}

export default ActiveJobs;
