'use client'

import { navigate } from './action'
import { useState, useEffect, useRef } from 'react'
import { IconPencilMinus } from "@tabler/icons-react"

export default function Home() {
  const [name, setName] = useState("") 
  const modal = useRef()
  const inputName = useRef()

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

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

  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">
          <label className="form-control w-full max-w-xs">
            <div className="label">
              <span className="label-text">What is your name?</span>
            </div>
            <input type="text" ref={inputName} defaultValue={name} placeholder="Name" className="input input-bordered w-full max-w-xs" />
          </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">Close</button>
            </form>
          </div>
        </div>
      </dialog>
      <h1 className="text-3xl">Bazaar</h1>
      <div className="flex flex-col space-y-4 items-center">
        <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>
  );
}
