'use client'

import { navigate } from './action'
import { useState, useEffect, useRef } from 'react'
import { IconPencilMinus, IconCamera, IconDice6 } from "@tabler/icons-react"
import { defaultAvatarImage } from './avatarImage'
import { getUsername } from './usernameGenerate'
import { resizeBase64Image, getBase64OfImage } from './utils'
import Webcam from 'react-webcam'

export default function Home() {
  const [name, setName] = useState("") 
  const [avatar, setAvatar] = useState(defaultAvatarImage)
  const [browserId, setBrowserId] = useState("")
  const [showWebcam, setShowWebcam] = useState(false)
  const webcamRef = useRef()
  const modal = useRef()
  const inputName = useRef()
  const inputProfilePicRef = useRef()

  function setUsername() {
    setName(inputName.current.value)
    localStorage.setItem("name", inputName.current.value)
  }

  function setAndStoreAvatar(data){
    resizeBase64Image(data).then((data) => {
      localStorage.setItem("avatar", data)
      setAvatar(data)
    })
  }

  function uuidv4() {
    return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, c =>
      (+c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> +c / 4).toString(16)
    );
  }

  function takePictureAvatar() {
    const imageSrc = webcamRef.current.getScreenshot()
    setAndStoreAvatar(imageSrc)
    setShowWebcam(false)
  }

  useEffect(() => {
    let localName = localStorage.getItem("name")
    let localAvatar = localStorage.getItem("avatar")
    let localBrowserId = localStorage.getItem("browserId")
    if(localName != null){
      setName(localName)
    } else {
      modal.current.showModal()
    }

    if(localAvatar != null) {
      setAvatar(localAvatar)
    }

    if(localBrowserId != null) {
      setBrowserId(localBrowserId)
    } else {
      let uuid = uuidv4()
      setBrowserId(uuid)
      localStorage.setItem("browserId", uuid)
    }
  }, [])

  return (
    <main data-theme="cupcake" className="flex min-h-screen flex-col items-center space-y-16 p-24">
      <dialog ref={modal} className="modal">
        <div className="modal-box flex flex-col space-y-4">
          <div className="avatar flex flex-col items-center space-y-4">
            <div className="w-24 rounded">
              <img src={avatar} />
            </div>
            { showWebcam &&
              <>
                <Webcam ref={webcamRef} />
                <button className="btn btn-primary" onClick={takePictureAvatar}><IconCamera /></button>
              </>
            }
            { !showWebcam &&
              <div className="flex flex-row space-x-4">
                <button className="btn btn-primary" onClick={() => {setShowWebcam(true)}}>Use Webcam</button>
                <button className="btn btn-primary" onClick={() => inputProfilePicRef.current.click() }>Select image</button>
                <input ref={inputProfilePicRef} type="file" onChange={(e) => {getBase64OfImage(e.target.files[0], (data) => setAndStoreAvatar(data))}} className="hidden"/>
              </div>
            }
          </div>
          <label className="form-control w-full">
            <div className="label">
              <span className="label-text">What is your name?</span>
            </div>
            <div className="flex flex-row w-full space-x-4">
              <input type="text" ref={inputName} defaultValue={name} placeholder="Name" className="input input-bordered w-full" />
              <button onClick={() => {inputName.current.value = getUsername()}} ><IconDice6 /></button>
            </div>
          </label>
          <div className="modal-action">
            <form method="dialog">
              {/* if there is a button in form, it will close the modal */}
              <button onClick={setUsername} className="btn">Save</button>
            </form>
          </div>
        </div>
      </dialog>
      <h1 className="text-6xl font-bold">✨ Tapage ✨</h1>
      <div className="flex flex-col space-y-4 items-center">
        <div className="avatar">
          <div className="w-24 rounded">
            <img src={avatar} />
          </div>
        </div>
        <div className="flex flex-row space-x-4">
          <span className="text-xl">{name}</span>
          <button onClick={() => { modal.current.showModal()}}>
            <IconPencilMinus />
          </button>
        </div>
      </div>
      <div className="flex flex-col space-y-4 items-center">
        <a href="/random" className="btn btn-primary">Create a room</a>
        <div className="divider"></div>
        <form action={navigate} className="flex flex-col space-y-4">
          <input type="text" name="id" placeholder="Room pin" className="input input-bordered w-full max-w-xs" />
          <button className="btn btn-primary">Join Room</button>
        </form>
      </div>
    </main>
  );
}
