import React, { useState, useEffect } from 'react'
import { Link, useLocation, useNavigate, useParams } from 'react-router-dom'
import SettingsDialogue from './SettingsDialogue'
import { Button } from './ui/button'
import { cn } from '@/lib/utils'
import { WikiIdBus } from '@/lib/eventBus/WikiIdBus'

import type { User } from '@/types'

type Props = { user:    User
               setUser: (user: User) => void }

const enum Menu { None,
                  Post,
                  Deerjikist,
                  Tag,
                  Wiki }


const TopNav: React.FC = ({ user, setUser }: Props) => {
  const location = useLocation ()
  const navigate = useNavigate ()

  const [settingsVsbl, setSettingsVsbl] = useState (false)
  const [selectedMenu, setSelectedMenu] = useState<Menu> (Menu.None)
  const [wikiId, setWikiId] = useState (WikiIdBus.get ())
  const [wikiSearch, setWikiSearch] = useState ('')
  const [activeIndex, setActiveIndex] = useState (-1)
  const [suggestions, setSuggestions] = useState<WikiPage[]> ([])
  const [suggestionsVsbl, setSuggestionsVsbl] = useState (false)

  const MyLink = ({ to, title, menu, base }: { to:    string
                                               title: string
                                               menu?: Menu
                                               base?: string }) => (
      <Link to={to} className={cn ('hover:text-orange-500 h-full flex items-center',
                                   (location.pathname.startsWith (base ?? to)
                                    ? 'bg-gray-700 px-4 font-bold'
                                    : 'px-2'))}>
        {title}
      </Link>)

  const whenWikiSearchChanged = e => {
    setWikiSearch (e.target.value)

    const q: string = e.target.value.split (' ').at (-1)
    if (!(q))
      {
        setSuggestions ([])
        return
      }
    // void (axios.get(`${ API_BASE_URL }/`))
  }

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter' && wikiSearch.length && (!(suggestionsVsbl) || activeIndex < 0))
      {
        navigate (`/wiki/${ encodeURIComponent (wikiSearch) }`)
        setSuggestionsVsbl (false)
      }
  }

  const handleTagSelect = (tag: Tag) => {
  }

  useEffect (() => {
    WikiIdBus.subscribe (setWikiId)
  }, [])

  useEffect (() => {
    if (location.pathname.startsWith ('/posts'))
      setSelectedMenu (Menu.Post)
    else if (location.pathname.startsWith ('/deerjikists'))
      setSelectedMenu (Menu.Deerjikist)
    else if (location.pathname.startsWith ('/tags'))
      setSelectedMenu (Menu.Tag)
    else if (location.pathname.startsWith ('/wiki'))
      setSelectedMenu (Menu.Wiki)
    else
      setSelectedMenu (Menu.None)
  }, [location])

  return (
      <>
        <nav className="bg-gray-800 text-white px-3 flex justify-between items-center w-full min-h-[48px]">
          <div className="flex items-center gap-2 h-full">
            <Link to="/posts" className="mx-4 text-xl font-bold text-orange-500">ぼざクリ タグ広場</Link>
            <MyLink to="/posts" title="広場" />
            <MyLink to="/deerjikists" title="ニジラー" />
            <MyLink to="/tags" title="タグ" />
            <MyLink to="/wiki/ヘルプ:ホーム" base="/wiki" title="Wiki" />
          </div>
          <div className="ml-auto pr-4">
            <Button onClick={() => setSettingsVsbl (true)}>{user?.name || '名もなきニジラー'}</Button>
            <SettingsDialogue visible={settingsVsbl}
                              onVisibleChange={setSettingsVsbl}
                              user={user}
                              setUser={setUser} />
          </div>
        </nav>
        {(() => {
          const className = 'bg-gray-700 text-white px-3 flex items-center w-full min-h-[40px]'
          const subClass = 'hover:text-orange-500 h-full flex items-center px-3'
          const inputBox = 'flex items-center px-3 mx-2'
          const Separator = () => <span className="flex items-center px-2">|</span>
          switch (selectedMenu)
          {
          case Menu.Post:
            return (
                <div className={className}>
                  <Link to="/posts" className={subClass}>一覧</Link>
                  <Link to="/posts/new" className={subClass}>投稿追加</Link>
                  <Link to="/wiki/ヘルプ:広場" className={subClass}>ヘルプ</Link>
                </div>)
          case Menu.Wiki:
            return (
                <div className={className}>
                  <input type="text"
                         className={inputBox}
                         placeholder="Wiki 検索"
                         value={wikiSearch}
                         onChange={whenWikiSearchChanged}
                         onFocus={() => setSuggestionsVsbl (true)}
                         onBlur={() => setSuggestionsVsbl (false)}
                         onKeyDown={handleKeyDown} />
                  <Link to="/wiki" className={subClass}>検索</Link>
                  <Link to="/wiki/new" className={subClass}>新規</Link>
                  <Link to="/wiki/changes" className={subClass}>全体履歴</Link>
                  <Link to="/wiki/ヘルプ:Wiki" className={subClass}>ヘルプ</Link>
                  {/^\/wiki\/(?!new|changes)[^\/]+/.test (location.pathname) &&
                      <>
                        <Separator />
                        <Link to={`/posts?tags=${ location.pathname.split ('/')[2] }`} className={subClass}>広場</Link>
                        <Link to={`/wiki/changes?id=${ wikiId }`} className={subClass}>履歴</Link>
                        <Link to={`/wiki/${ wikiId || location.pathname.split ('/')[2] }/edit`} className={subClass}>編輯</Link>
                      </>}
                </div>)
          }
        }) ()}
      </>)
}


export default TopNav
