import React, { Suspense, useState } from 'react';
import { QrCodeScanner } from '@digigov/ui/app/QrCodeScanner';
import { ErrorSummary } from '@digigov/ui/feedback/ErrorSummary';
import { Heading } from '@digigov/ui/typography/Heading';

export const Default = (_: any) => {
  const [error, setError] = useState({ message: '' });
  const validate = (rawData) => {
    if (rawData) {
      const url = new URL(rawData);
      return url.origin === window.location.origin;
    } else {
      return false;
    }
  };
  const handleScan = (data) => {
    if (data) {
      const url = new URL(data);
      setError({ message: '' });
      alert('The page will navigate to ' + url.pathname);
      // or you can use the router to redirect like so:
      // eg. router.push(url.pathname);
    }
  };
  const handleError = () => {
    setError({ message: 'scan.data_error' });
  };

  return (
    <Suspense fallback={<div>Loading...</div>}>
      <QrCodeScanner
        style={{ maxWidth: '400px' }}
        validate={validate}
        onScan={handleScan}
        onError={handleError}
      >
        {error.message && (
          <ErrorSummary>
            <Heading size="sm">{error.message}</Heading>
          </ErrorSummary>
        )}
      </QrCodeScanner>
    </Suspense>
  );
};

export default Default;
