import React, {useState, useEffect} from "react";
import { useParams } from "react-router-dom";
import { CustomerService, SignatureRequestService } from "../../services";
import SignatureCanvas from 'react-signature-canvas';
import moment from 'moment';

const DriverSignature = () => {
  const urlParams = useParams();
  const [signatureRequest, setSignatureRequest] = useState(undefined);

  const clearCanvas = () => {
      const canvas = document.getElementsByClassName('sigCanvas')[0];
      if (canvas) {
        const context = canvas.getContext('2d');
        context.clearRect(0, 0, canvas.width, canvas.height);
      }

  }

  const submitSignature = () => {
    const fabricCanvas = document.getElementsByClassName('sigCanvas')[0];
    if (!fabricCanvas || !signatureRequest?.id) {
      window.alert('Signature request is not ready. Please refresh and try again.');
      return;
    }
    const routeId = `${signatureRequest?.route_id || ''}`.trim();
    const driverId = `${signatureRequest?.driver_id || ''}`.trim();
    const dateArr = moment(signatureRequest?.route_date)?.format('MM/DD/YYYY')?.split('/') || [];
    const month = `${dateArr[0] || ''}`.trim();
    const day = `${dateArr[1] || ''}`.trim();
    if (!routeId || !driverId || !month || !day || month.toLowerCase().includes('invalid')) {
      window.alert('Invalid route signature key. Please ask admin to regenerate signature link.');
      return;
    }
    const fileName = `${routeId}_${driverId}_${month}_${day}`;
    const scaledCanvas = document.createElement('canvas');

    scaledCanvas.width = 400;
    scaledCanvas.height = 200;

    const ctx = scaledCanvas.getContext('2d');
    ctx.drawImage(fabricCanvas, 0, 0, scaledCanvas.width, scaledCanvas.height);
    scaledCanvas.toBlob(function(blob) {
      if (!blob) {
        window.alert('Failed to read signature image. Please draw signature again.');
        return;
      }
      const formData = new FormData();
      formData.append('file', blob, `${fileName}.jpg`);
      
      CustomerService.uploadDriverSignature(fileName, formData, {
        year: moment(signatureRequest?.route_date).format('YYYY')
      }).then(() => {
        SignatureRequestService.updateSignatureRequest(signatureRequest?.id, { status: 'done'}).then(() => {
            SignatureRequestService.getSignatureRequestById(urlParams.id).then((data) => {
              setSignatureRequest(data?.data);
            })
        })
      }).catch(() => {
        window.alert('Failed to upload signature. Please try again.');
      });
    })
  }

  useEffect(() => {
    SignatureRequestService.getSignatureRequestById(urlParams.id).then((data) => {
      setSignatureRequest(data?.data);
    })
  }, []);


  return (
    <>
      <div className="list row mb-4">
        <div className="col-md-12 text-primary">
           <h5>Driver Signature Collection</h5> 
        </div>
        {
            signatureRequest?.status === 'done' &&
            <div className="list row">
				<div className="col-md-12">
                    The signature has been submitted. 
                </div>
            </div>
        }
            
        {
            signatureRequest?.status === 'active' && 
            <div className="list row">
				<div className="col-md-12">
                    <div>Draw your signature below:</div>
                    <SignatureCanvas penColor='black'
                    canvasProps={{width: 1000, height: 500, className: 'sigCanvas'}} />
                </div>
                <div className="col-md-12">
                    <button className="btn btn-primary me-2" onClick={() => submitSignature()}>Submit</button>
                    <button className="btn btn-default" onClick={() => clearCanvas()}>Clear</button>
                </div>
            </div>
        }

        {
            (!signatureRequest || signatureRequest?.status === 'inactive') && 
            <div className="list row">
				<div className="col-md-12">
                    Invalid Sigature Request
                </div>
            </div>
        }
        
      </div>
      <></>
    </>
      
  );
};

export default DriverSignature;