'use client';

import React, { useEffect, useState } from 'react';
import { QrReader } from 'react-qr-reader';
import { useRouter } from 'next/navigation';

import { removeBaseUrl } from '@/utils/removeBaseUrl';

import styles from './QrcodeScanner.module.scss';

export default function QrcodeScanner({ lang }: { lang?: string}) {
  const router = useRouter();

  const [result, setResult] = useState<string>('');

  const onResult = (r: any) => {
    if (!!r?.text?.length && r?.text !== result ) {
      setResult(r.text);
    }
  };

  useEffect(() => {
    if (!!router && !!lang?.length && !!result?.length) {
      router.replace(removeBaseUrl(result, lang));
    }
  }, [lang, result, router]);

  return (
    <div className={styles.QrcodeScanner}>
      <QrReader
        key="environment"
        constraints={{ facingMode: 'environment', aspectRatio: 1 }}
        videoStyle={{ backgroundColor: '#000000' }}
        onResult={onResult}
      />
      <div className={styles['camera-target']}>
        {['left', 'right'].map((x) => ['top', 'bottom'].map((y) => (
          <span key={`${y}-${x}`} className={styles[`target-corner--${y}-${x}`]} />
        )))}
      </div>
    </div>
  );
};
