import { useState } from 'react';

import { constructAddWordUiCommand } from 'contract.cm';
import { QRCodeSVG } from 'qrcode.react';

export const App = () => {
  const [word, setWord] = useState('');
  const [qrCode, setQrCode] = useState('');

  const onSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setQrCode(constructAddWordUiCommand({ word, contractId: import.meta.env.VITE_CONTRACT_ADDRESS ?? '' }));
  };

  return (
    <div>
      <form onSubmit={onSubmit}>
        <div className="mx-auto my-10 flex max-w-2xl flex-col gap-2">
          <label htmlFor="first_name" className="mb-2 block text-sm font-medium text-gray-900 dark:text-white">
            Word
          </label>
          <input
            type="text"
            id="first_name"
            className="block w-full rounded-lg border border-gray-300 bg-gray-50 p-2.5 text-sm text-gray-900 focus:border-blue-500 focus:ring-blue-500 dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400 dark:focus:border-blue-500 dark:focus:ring-blue-500"
            placeholder="Happiness"
            required
            value={word}
            onChange={(e) => setWord(e.target.value)}
          />
          <button
            type="submit"
            className="w-full self-end rounded-lg bg-blue-700 px-5 py-2.5 text-center text-sm font-medium text-white hover:bg-blue-800 focus:outline-none focus:ring-4 focus:ring-blue-300 sm:w-auto dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800"
          >
            Submit
          </button>
        </div>
      </form>
      <div className="flex w-full justify-center py-4">
        <QRCodeSVG
          onClick={() => {
            navigator.clipboard.writeText(qrCode).catch((err) => {
              console.error(err);
            });
          }}
          value={qrCode}
          size={320}
          level="L"
          className="hover:cursor-pointer"
          bgColor="transparent"
          fgColor="black"
        />
      </div>
    </div>
  );
};
