After pressing “Proceed” button it is not moving further in mobile phone browsers.
Published: 2024-02-21 03:28:34

import React, { useEffect, useState } from 'react';
import { db } from '../../firebaseconfig';
import {
  collection,
  addDoc,
  onSnapshot,
  doc,
  query,
  where,
  orderBy,
  limit,
  getDocs
} from 'firebase/firestore';
import soundA from './path_to_sound_A.mp3';
import domtoimage from 'dom-to-image';
import { saveAs } from 'file-saver';
import "./screenP.css";

const ScreenP = () => {
  const [mobileNumber, setMobileNumber] = useState('');
  const [existingMobileNumber, setExistingMobileNumber] = useState('');
  const [name, setName] = useState('');
  const [status, setStatus] = useState('');
  const [patientId, setPatientId] = useState(null);
  const [patientDetails, setPatientDetails] = useState(null);
  const [nowServingToken, setNowServingToken] = useState('');
  const [isProcessing, setIsProcessing] = useState(false);
  const [proceedClicked, setProceedClicked] = useState(false);

  useEffect(() => {
    if (patientId) {
      const unsubscribe = onSnapshot(doc(db, 'patients', patientId), (doc) => {
        const patientData = doc.data();
        setPatientDetails(patientData);

        if (patientData.status !== status) {
          setStatus(patientData.status);
          vibrateAndPlaySound();
        }

        if (patientData.doctorAssigned && ['C', 'D', 'E', 'F'].includes(patientData.status)) {
          const servingTokenQuery = query(collection(db, 'patients'), where('status', '==', 'D'), where('doctorAssigned', '==', patientData.doctorAssigned));
          const unsubscribeServingToken = onSnapshot(servingTokenQuery, (snapshot) => {
            const serving = snapshot.docs.map(doc => doc.data()).find(p => p.doctorAssigned === patientData.doctorAssigned);
            if (serving) {
              setNowServingToken(serving.tokenNumber);
            } else {
              setNowServingToken('');
            }
          });

          return () => unsubscribeServingToken();
        }
      });

      return () => unsubscribe();
    }
  }, [patientId, status]);

  const vibrateAndPlaySound = () => {
    if ('vibrate' in navigator) {
      navigator.vibrate(500);
    }
    const audio = new Audio(soundA);
    audio.play().catch((error) => console.error('Audio playback failed:', error));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      setProceedClicked(true);
      setIsProcessing(true); // Disable the button and indicate processing
      const docRef = await addDoc(collection(db, 'patients'), {
        mobileNumber,
        name,
        status: 'A',
        requestTime: new Date(),
        tag: 'QR',
      });
      setPatientId(docRef.id);
      setStatus('A');
      vibrateAndPlaySound();
    } catch (error) {
      console.error('Error adding document: ', error);
    } finally {
      setIsProcessing(false); // Enable the button after processing
    }
  };

  const fetchLatestToken = async () => {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const patientsQuery = query(
      collection(db, 'patients'),
      where('mobileNumber', '==', existingMobileNumber),
      where('requestTime', '>=', today),
      orderBy('requestTime', 'desc'),
      limit(1)
    );

    const querySnapshot = await getDocs(patientsQuery);
    const latestPatient = querySnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }))[0];

    if (latestPatient) {
      setPatientDetails(latestPatient);
      setPatientId(latestPatient.id);
      setStatus(latestPatient.status);
      setName(latestPatient.name);
      setMobileNumber(latestPatient.mobileNumber);
    } else {
      alert('No token found for the given mobile number today.');
    }
  };

  const takeScreenshot = () => {
    const patientDetailsElement = document.querySelector('.patient-details');
    domtoimage.toBlob(patientDetailsElement)
      .then(function (blob) {
        saveAs(blob, 'token-details.png');
      })
      .catch(function (error) {
        console.error('Error taking screenshot:', error);
      });
  };


  const displayMessage = () => {
    if (!patientDetails) return null;

    let messageClass = 'message ' + 'status-' + patientDetails.status;
    switch (patientDetails.status) {
      case 'A':
        return <div className={messageClass}>Kindly wait. <br/>We are processing your request</div>;
      case 'B':
        return <div className={messageClass}>Kindly go to the Reception to make the payment.</div>;
      case 'C':
        return (
          <div className={messageClass}>
            <span className="token-number">Your Token Number: {patientDetails.tokenNumber}</span><br />
            Doctor Assigned: {patientDetails.doctorAssigned}<br />
            Doctor's Room: {patientDetails.doctorRoom}<br />
            <div>Wait for your Token Number</div>
            <button onClick={takeScreenshot}>Take Screenshot</button>
            <div className='nowServingToken'>Now Serving Token: {nowServingToken}</div>
          </div>
        );
        case 'D':
          return (
              <div className={messageClass}>
                 <span className="token-number">Your Token Number: {patientDetails.tokenNumber}</span><br />
                  <p>The doctor has called you.</p>
                  <p>Please go to the Doctor's room now</p>
      
                  <p>
                     
                      Doctor Assigned: {patientDetails.doctorAssigned}<br />
                      Doctor's Room: {patientDetails.doctorRoom}
                  </p>
                  
                  <div className='nowServingToken'>
                      Now Serving Token: {nowServingToken}
                  </div>
              </div>
          );
      
      case 'E':
        return <div className={messageClass}>
          <span className="token-number">Your Token Number: {patientDetails.tokenNumber}</span><br />
          
          Consultation Completed. Thank you for visiting us!</div>;
      case 'F':
        return <div className={messageClass}>You didn't show up for the consultation. Please contact the Reception.</div>;
      default:
        return <div className={messageClass}>Status not recognized.</div>;
    }
  };

  return (
    <div className="screenP-container">
      {patientId ? (
        <div className="patient-details">
          <h2 className='titleP'>Please find the details below</h2>
          <p><strong>Your Name:</strong> {name}</p>
          <p><strong>Your Mobile Number:</strong> {mobileNumber}</p>
          {displayMessage()}
        </div>
      ) : (
        <div>
          <form className="form-container" onSubmit={handleSubmit}>
            <input
              className="input-field"
              type="text"
              value={mobileNumber}
              onChange={(e) => setMobileNumber(e.target.value)}
              placeholder="Mobile Number without country code"
              required
            />
            <input
              className="input-field"
              type="text"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="Name of the patient"
              required
            />
            {!proceedClicked && (
              <button
                className="proceed-button"
                type="submit"
                disabled={isProcessing} // Disable the button if processing
              >
                {isProcessing ? 'Processing' : 'Proceed'}
              </button>
            )}
          </form>
          {proceedClicked && isProcessing && <div className="processing-message">Processing...</div>}
          <div className="mobile-number-lookup">
            <p className='alreadytext'>Already have a token? <br/>Enter your mobile number to check the latest status.</p>
            <input
              className="ALRDYinput-field"
              type="text"
              value={existingMobileNumber}
              onChange={(e) => setExistingMobileNumber(e.target.value)}
              placeholder="Enter your Mobile Number without country code"
            />
            <button className="check-status-button" onClick={fetchLatestToken}>Check Status</button>
          </div>
        </div>
      )}
    </div>
  );
};

export default ScreenP;