'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 Webcam from 'react-webcam'

export default function Home() {
  const [name, setName] = useState("") 
  const [avatar, setAvatar] = useState(defaultAvatarImage)
  const [showWebcam, setShowWebcam] = useState(false)
  const webcamRef = useRef()
  const modal = useRef()
  const inputName = 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 takePictureAvatar() {
    const imageSrc = webcamRef.current.getScreenshot()
    setAndStoreAvatar(imageSrc)
    setShowWebcam(false)
  }

  function getBase64OfImage(file, cb) {
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function () {
        cb(reader.result)
    };
    reader.onerror = function (error) {
        console.log('Error: ', error);
    };
  }

  function resizeBase64Image(base64Image) {
    return new Promise((resolve, reject) => {
      const maxSizeInKB = 500;
      const maxSizeInBytes = maxSizeInKB * 1024;
      const img = new Image();
      img.src = base64Image;
      img.onload = function () {
        const canvas = document.createElement("canvas");
        const ctx = canvas.getContext('2d');
        const width = img.width;
        const height = img.height;
        const aspectRatio = width / height;
        const newWidth = Math.sqrt(maxSizeInBytes * aspectRatio);
        const newHeight = Math.sqrt(maxSizeInBytes / aspectRatio);
        canvas.width = newWidth;
        canvas.height = newHeight;
        ctx.drawImage(img, 0, 0, newWidth, newHeight);
        let quality = 0.8;
        let dataURL = canvas.toDataURL('image/jpeg', quality);
        resolve(dataURL);
      };
    });
  }

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

    if(localAvatar != null) {
      setAvatar(localAvatar)
    }
  }, [])

  return (
    <main data-theme="light" 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 &&
              <>
                <button className="btn btn-primary" onClick={() => {setShowWebcam(true)}}>Use Webcam</button>
                <input type="file" onChange={(e) => {getBase64OfImage(e.target.files[0], (data) => setAndStoreAvatar(data))}} className="file-input w-full max-w-xs"/>
              </>
            }
          </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-3xl">Bazaar</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>
  );
}
