import React, {useState, useEffect} from "react";
import { useSelector } from "react-redux";
import { useParams, useNavigate } from "react-router-dom";
import { selectAllRoutes, selectTomorrowAllRoutes, selectAllActiveDrivers, selectAllActiveVehicles, selectHistoryRoutes } from "./../../store";
import PersonnelSection from "./PersonnelSection";
import { Modal, Button } from "react-bootstrap";
import { AuthService, CustomerService, SignatureRequestService } from "../../services";
import moment from 'moment';

const RouteView = () => {
  const params = useParams();
  const allRoutes = useSelector(selectAllRoutes);
  const tomorrowRoutes = useSelector(selectTomorrowAllRoutes);
  const historyRoutes = useSelector(selectHistoryRoutes);
  const drivers = useSelector(selectAllActiveDrivers);
  const vehicles = useSelector(selectAllActiveVehicles);
  const currentRoute = (allRoutes.find(item => item.id === params.id)) || (tomorrowRoutes.find(item => item.id === params.id)) || (historyRoutes.find(item => item.id === params.id));
  const currentVehicle = vehicles.find(item => item.id === currentRoute?.vehicle );
  const currentDriver = drivers.find(item => item.id === currentRoute?.driver);
  const [showVehicleDetails, setShowVehicleDetails] = useState(false);
  const [signature, setSignature] = useState(undefined);
  const [signatureRequest, setSignatureRequest] = useState(undefined);
  const paramsQuery = new URLSearchParams(window.location.search);
  const scheduleDate = paramsQuery.get('dateSchedule');

  const navigate = useNavigate();
  const closeModal = () => {
    setShowVehicleDetails(false);
  }
  const openModal = () => {
    setShowVehicleDetails(true);
  }
  const getRelatedOutboundRoutesForThisView = () => {
    if (allRoutes.find(item => item.id === params.id)) {
      return allRoutes.filter(item => item.type==='outbound');
    }
    if (tomorrowRoutes.find(item => item.id === params.id)) {
      return tomorrowRoutes.filter(item => item.type==='outbound');
    }
    if (historyRoutes.find(item => item.id === params.id)) {
      return historyRoutes.filter(item => item.type==='outbound');
    }
  }
  const directToDashboad = () => {
    if (tomorrowRoutes.find(item => item.id === params.id)) {
      navigate(`/trans-routes/schedule?dateSchedule=${moment(tomorrowRoutes.find(item => item.id === params.id).schedule_date).format('YYYY-MM-DD')}`);
    } else {
      if (historyRoutes.find(item => item.id === params.id)) {
        navigate(`/trans-routes/history`);
      } else {
        navigate(`/trans-routes/dashboard`);
      }
    }
  }
  const edit = () => {
    if (scheduleDate) {
      navigate(`/trans-routes/edit/${currentRoute?.id}?dateSchedule=${scheduleDate}`)
    } else {
      navigate(`/trans-routes/edit/${currentRoute?.id}`)
    }
  }
  const deleteFile = () => {
    if (signature) {
      const dateArr = moment(currentRoute?.schedule_date)?.format('MM/DD/YYYY')?.split('/') || [];
      CustomerService.deleteFile({name: `${currentRoute?.id}_${currentRoute?.driver}_${dateArr[0]}_${dateArr[1]}`}).then(data => {
        setSignature(undefined);
      })
    }
  }
  const generateSignatureRequest = () => {
    SignatureRequestService.createNewSignatureRequest({
      driver_id: currentDriver?.id,
      driver_name: currentDriver?.name,
      route_id: currentRoute?.id,
      route_date: currentRoute?.schedule_date,
      route_name: currentRoute?.name,
      status: 'active',
    }).then((data) => {
      setSignatureRequest(data.data);
    })
  }
  useEffect(() => {
    const dateArr = moment(currentRoute?.schedule_date)?.format('MM/DD/YYYY')?.split('/') || [];
       
    CustomerService.getAvatar(`${currentRoute?.id}_${currentRoute?.driver}_${dateArr[0]}_${dateArr[1]}`).then(data => {
      setSignature(data.data);
    });
    SignatureRequestService.getAllSignatureRequests({driver_id: currentDriver?.id, route_id: currentRoute?.id, route_date: currentRoute?.scheduleDate}).then((data) => {
      if (data?.data?.length > 0) {
        setSignatureRequest(data?.data[0]);
      }
    })
  }, [currentRoute]);
  return (
    <>
      <div className="list row">
        <div className="col-md-12 text-primary mb-2">
          <h5>{currentRoute?.name} <button className="btn btn-link btn-sm" onClick={() => directToDashboad()}>Back</button> {AuthService.canAddOrEditRoutes() && <button className="btn btn-primary btn-sm" onClick={() => edit()}>Update</button>}</h5>
        </div>
      </div>
      <div className="list row mb-4">
        <div className="col-md-4 col-sm-6 col-xs-6">
          <div className="mb-2">Vehicle Number: {currentVehicle?.vehicle_number} <button type="button" className="btn btn-info btn-sm" onClick={() => openModal()}>Vehicle Details</button></div>
          <div className="mb-2">Total Customers: {currentRoute?.route_customer_list?.length || 0}</div>
          <div className="mb-2">Driver Name: {currentDriver?.name}</div>
          <div className="mb-2">Route Type: { currentRoute?.type }</div>
          {signature && <div className="mb-2">Driver Signature: {signature && <img width="100px" src={`data:image/jpg;base64, ${signature}`}/>}</div>}
          {!signature && !signatureRequest && <div className="mb-2"><button className="btn btn-sm btn-primary" onClick={() => generateSignatureRequest()}>Generate Signature Link For Driver</button></div>}
        </div>
        <div className="col-md-4 col-sm-6 col-xs-6">
          <div className="mb-2">Route Start Time: {currentRoute?.start_time && (new Date(currentRoute?.start_time))?.toLocaleTimeString()}</div>
          <div className="mb-2">Route End Time: {currentRoute?.end_time && (new Date(currentRoute?.end_time))?.toLocaleTimeString()}</div>
          {currentRoute?.type === 'inbound' && <div className="mb-2">Arrive Center Time: {currentRoute?.end_time && (new Date(currentRoute?.end_time))?.toLocaleTimeString()}</div>}
          {currentRoute?.type === 'outbound' &&<div className="mb-2">Leave Center Time: {currentRoute?.start_time && (new Date(currentRoute?.start_time))?.toLocaleTimeString()}</div>}
          {currentRoute?.type === 'outbound' && <div className="mb-2">Estimated Start Time: {currentRoute?.estimated_start_time && (new Date(currentRoute?.estimated_start_time))?.toLocaleTimeString()}</div>}
        </div>
        <div className="col-md-4 col-sm-6 col-xs-6">
          <div className="mb-2">Start Mileage: { currentRoute?.start_mileage}</div>
          <div className="mb-2">End Mileage: { currentRoute?.end_mileage}</div>

        </div>
        <div className="col-md-12">{!signature && signatureRequest &&  <div className="alert alert-success fade show mb-2 mt-2" role="alert">
              <div>Please send this to the driver to get signature:</div>
              <div>{`${window.location.origin}/signature/${signatureRequest?.id}`}</div>
            </div>}</div>
      </div>
      <div className="list row">
        <div className="col-md-12 mb-4">
          {currentRoute && <PersonnelSection transRoutes={[currentRoute]} showCompletedInfo={true} showGroupInfo={true} isInbound={currentRoute?.type === 'inbound' } allowForceEdit={AuthService.canViewRoutes()} sectionName="Personnel Status (click on each user to edit)" relatedOutbound={getRelatedOutboundRoutesForThisView()} vehicle={currentVehicle} driverName={currentDriver?.name} deleteFile={deleteFile}/>}
        </div>
      </div>
      <br></br>
      <div className="list row">
        <div className="col-md-12 mb-4"><h5>Checklist:</h5>
          {currentRoute && currentRoute?.checklist_result?.map(item => <div>{`${item?.item}: ${item?.result ? 'Yes': "No"}`}</div>)}
          {currentRoute && currentRoute?.checklist_result.length === 0 && <>No Checklist found</>}
        </div>
      </div>
     
      <Modal show={showVehicleDetails} onHide={() => closeModal()}>
        <Modal.Header closeButton>
          <Modal.Title>Vehicle Info</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <>
            <div className="mb-2">Vehicle Number: {currentVehicle?.vehicle_number}</div>
            <div className="mb-2">Tag: {currentVehicle?.tag}</div>
            <div className="mb-2">EzPass: {currentVehicle?.ezpass}</div>
            <div className="mb-2">GPS: {currentVehicle?.gps_tag}</div>
            <div className="mb-2">Capacity: {currentVehicle?.capacity}</div>
            <div className="mb-2">Status: {currentVehicle?.status}</div>
            <div className="mb-2">Mileage: {currentVehicle?.mileage}</div>
          </>
        </Modal.Body>
        <Modal.Footer>
          <Button variant="secondary" onClick={() => closeModal()}>
            Close
          </Button>
        </Modal.Footer>
      </Modal>

    </>
  );
};

export default RouteView;