import type { Contract } from 'ethers'
import { ethers } from 'ethers'
import { useRef, useState } from 'react'

const Web3 = () => {
  const moodInputRef = useRef()
  const [mood, setMood] = useState()
  //@ts-ignore
  const provider = new ethers.providers.Web3Provider(window.ethereum, 'ropsten')
  const contractAddress = '0x0335e801159Af04b3067bED0aeeaCC86Ece51e19'
  const moodAbi = [
    {
      constant: true,
      inputs: [],
      name: 'getMood',
      outputs: [
        {
          internalType: 'string',
          name: '',
          type: 'string',
        },
      ],
      signature: '0x9d0c1397',
      stateMutability: 'view',
      type: 'function',
    },
    {
      inputs: [
        {
          internalType: 'string',
          name: '_mood',
          type: 'string',
        },
      ],
      name: 'setMood',
      outputs: [],
      signature: '0x5f3cbff5',
      stateMutability: 'nonpayable',
      type: 'function',
    },
  ]

  let contract: Contract
  let signer

  provider.send('eth_requestAccounts', []).then(() => {
    provider.listAccounts().then(function (accounts) {
      signer = provider.getSigner(accounts[0])
      contract = new ethers.Contract(contractAddress, moodAbi, signer)
    })
  })

  async function getMoodAbi() {
    const getMoodPromise = contract.getMood()
    const currentMood = await getMoodPromise
    setMood(currentMood)
  }

  async function setMoodAbi() {
    //@ts-ignore
    const setMoodPromise = contract.setMood(moodInputRef.current.value)
    await setMoodPromise
  }

  return (
    <div>
      <div className="container mx-auto">
        <p className="mb-6 text-2xl">Web3 Playground</p>
        <div className="grid-rows-1 mt-3">
          <div>
            <p className="text-xl">dApp</p>

            <input
              id="mood"
              //@ts-ignore
              ref={moodInputRef}
              type="text"
              className="input border-secondary w-full max-w-xs border-2"
            />
            <button className="btn bg-secondary" onClick={setMoodAbi}>
              Set Mood
            </button>

            <div className="card bg-primary text-primary-content w-40">
              <div className="card-body">
                <h2 className="card-title justify-center">{mood}</h2>
                <div className="card-actions justify-center">
                  <button className="btn" onClick={getMoodAbi}>
                    Get Mood
                  </button>
                </div>
              </div>
            </div>
          </div>
          <div>
            <p className="text-xl">NFT</p>
          </div>
        </div>
      </div>
    </div>
  )
}

export default Web3
