import React from 'react'

const OPENING_OR_OPEN = new Set(['opening', 'open'])

export default function SearchOverlay({
  phase,
  query,
  inputRef,
  loading,
  artworks,
  groups,
  users,
  tags,
  activeIdx,
  onQueryChange,
  onClose,
  onSubmit,
  onKeyDown,
  onNavigate,
}) {
  if (phase === 'closed') return null

  const hasResults = artworks.length > 0 || groups.length > 0 || users.length > 0 || tags.length > 0
  const isVisible = OPENING_OR_OPEN.has(phase)

  return (
    <div
      className={`fixed inset-0 z-[1000] md:hidden transition-opacity ${isVisible ? 'opacity-100' : 'opacity-0'} ${phase === 'closing' ? 'duration-150' : 'duration-200'} ease-out`}
      aria-modal="true"
      role="dialog"
      aria-label="Search overlay"
    >
      <div className="absolute inset-0 bg-nova/95 backdrop-blur-sm" onClick={onClose} aria-hidden="true" />

      <div className={`relative h-full w-full bg-nova border-t border-white/[0.06] transform transition-transform ${isVisible ? 'translate-y-0' : '-translate-y-3'} ${phase === 'closing' ? 'duration-150' : 'duration-200'} ease-out`}>
        <form onSubmit={onSubmit} role="search" className="h-full">
          <div className="h-[72px] px-3 border-b border-white/[0.08] flex items-center gap-2">
            <button
              type="button"
              onClick={onClose}
              aria-label="Back"
              className="w-11 h-11 rounded-lg inline-flex items-center justify-center text-white/80 hover:bg-white/10 hover:text-white transition-colors"
            >
              <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="2.25">
                <path strokeLinecap="round" strokeLinejoin="round" d="M15 18l-6-6 6-6" />
              </svg>
            </button>

            <div className="relative flex-1">
              <svg className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-soft pointer-events-none" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="2" aria-hidden="true">
                <path strokeLinecap="round" strokeLinejoin="round" d="M21 21l-4.35-4.35M17 11A6 6 0 1 1 5 11a6 6 0 0 1 12 0z"/>
              </svg>
              <input
                ref={inputRef}
                type="search"
                role="combobox"
                value={query}
                onChange={(e) => onQueryChange(e.target.value)}
                onKeyDown={onKeyDown}
                placeholder="Search artworks, groups, creators, tags..."
                aria-label="Search"
                aria-autocomplete="list"
                aria-haspopup="listbox"
                aria-expanded={hasResults}
                aria-controls="sb-mobile-suggestions"
                aria-activedescendant={activeIdx >= 0 ? `sb-mobile-item-${activeIdx}` : undefined}
                autoComplete="off"
                className="w-full h-11 bg-white/[0.06] border border-white/[0.12] rounded-lg py-0 pl-9 pr-9 text-sm text-white placeholder-soft outline-none focus:border-accent focus:ring-1 focus:ring-accent/30 transition-colors"
              />
              {loading && (
                <svg className="absolute right-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5 animate-spin text-soft" fill="none" viewBox="0 0 24 24" aria-hidden="true">
                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"/>
                  <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8z"/>
                </svg>
              )}
            </div>

            <button
              type="button"
              onClick={onClose}
              aria-label="Close search"
              className="w-11 h-11 rounded-lg inline-flex items-center justify-center text-white/80 hover:bg-white/10 hover:text-white transition-colors"
            >
              <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="2.25">
                <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>

          <div className="overflow-y-auto overscroll-contain" style={{ height: 'calc(100vh - 72px)' }}>
            {hasResults ? (
              <ul
                id="sb-mobile-suggestions"
                role="listbox"
                aria-label="Search suggestions"
                className="mx-2 my-2 px-2 py-2 rounded-xl border border-white/[0.10] bg-nova-900/95 backdrop-blur-sm shadow-2xl"
              >
                {artworks.length > 0 && (
                  <>
                    <li role="presentation" className="px-3 pt-2 pb-1 text-[10px] font-semibold uppercase tracking-wider text-white/35 select-none">Artworks</li>
                    {artworks.map((item, i) => (
                      <li key={item.slug ?? i} role="option" id={`sb-mobile-item-${i}`} aria-selected={activeIdx === i}>
                        <button
                          type="button"
                          onClick={() => onNavigate({ type: 'artwork', ...item })}
                          className={`w-full min-h-12 flex items-center gap-3 px-3 py-2 text-left rounded-lg transition-colors ${activeIdx === i ? 'bg-white/[0.14]' : 'hover:bg-white/[0.08]'}`}
                        >
                          {item.thumbnail_url ? (
                            <img src={item.thumbnail_url} alt="" aria-hidden="true" className="w-10 h-10 rounded-lg object-cover shrink-0" loading="lazy" />
                          ) : (
                            <span className="w-10 h-10 rounded-lg bg-white/[0.04] border border-white/[0.08] shrink-0" aria-hidden="true" />
                          )}
                          <div className="min-w-0">
                            <div className="text-sm font-medium text-white truncate">{item.title}</div>
                            {item.author?.name && <div className="text-xs text-neutral-400 truncate">by {item.author.name}</div>}
                          </div>
                        </button>
                      </li>
                    ))}
                  </>
                )}

                {groups.length > 0 && (
                  <>
                    <li role="presentation" className={`px-3 pb-1 text-[10px] font-semibold uppercase tracking-wider text-white/35 select-none ${artworks.length > 0 ? 'pt-2 border-t border-white/[0.06]' : 'pt-2'}`}>Groups</li>
                    {groups.map((group, j) => {
                      const flatIdx = artworks.length + j
                      return (
                        <li key={group.slug ?? group.id ?? j} role="option" id={`sb-mobile-item-${flatIdx}`} aria-selected={activeIdx === flatIdx}>
                          <button
                            type="button"
                            onClick={() => onNavigate({ type: 'group', ...group })}
                            className={`w-full min-h-12 flex items-center gap-3 px-3 py-2 text-left rounded-lg transition-colors ${activeIdx === flatIdx ? 'bg-white/[0.14]' : 'hover:bg-white/[0.08]'}`}
                          >
                            {group.avatar_url ? (
                              <img src={group.avatar_url} alt="" aria-hidden="true" className="w-10 h-10 rounded-2xl object-cover shrink-0 bg-white/[0.04] border border-white/[0.08]" loading="lazy" />
                            ) : (
                              <span className="w-10 h-10 rounded-2xl bg-white/[0.04] border border-white/[0.08] inline-flex items-center justify-center shrink-0" aria-hidden="true">
                                <i className="fa-solid fa-people-group text-white/45" />
                              </span>
                            )}
                            <div className="min-w-0">
                              <div className="text-sm font-medium text-white truncate">{group.name}</div>
                              <div className="text-xs text-neutral-400 truncate">{group.headline || `${Number(group.counts?.followers || group.followers_count || 0).toLocaleString()} followers`}</div>
                            </div>
                          </button>
                        </li>
                      )
                    })}
                  </>
                )}

                {users.length > 0 && (
                  <>
                    <li role="presentation" className={`px-3 pb-1 text-[10px] font-semibold uppercase tracking-wider text-white/35 select-none ${artworks.length > 0 || groups.length > 0 ? 'pt-2 border-t border-white/[0.06]' : 'pt-2'}`}>Creators</li>
                    {users.map((user, j) => {
                      const flatIdx = artworks.length + groups.length + j
                      return (
                        <li key={user.username} role="option" id={`sb-mobile-item-${flatIdx}`} aria-selected={activeIdx === flatIdx}>
                          <button
                            type="button"
                            onClick={() => onNavigate({ type: 'user', ...user })}
                            className={`w-full min-h-12 flex items-center gap-3 px-3 py-2 text-left rounded-lg transition-colors ${activeIdx === flatIdx ? 'bg-white/[0.14]' : 'hover:bg-white/[0.08]'}`}
                          >
                            <img src={user.avatar_url} alt="" aria-hidden="true" className="w-10 h-10 rounded-full object-cover shrink-0 bg-white/[0.04] border border-white/[0.08]" loading="lazy" />
                            <div className="min-w-0">
                              <div className="text-sm font-medium text-white truncate">@{user.username}</div>
                              {user.uploads > 0 && <div className="text-xs text-neutral-400">{user.uploads.toLocaleString()} uploads</div>}
                            </div>
                          </button>
                        </li>
                      )
                    })}
                  </>
                )}

                {tags.length > 0 && (
                  <>
                    <li role="presentation" className={`px-3 pb-1 text-[10px] font-semibold uppercase tracking-wider text-white/35 select-none ${artworks.length > 0 || groups.length > 0 || users.length > 0 ? 'pt-2 border-t border-white/[0.06]' : 'pt-2'}`}>Tags</li>
                    {tags.map((tag, j) => {
                      const flatIdx = artworks.length + groups.length + users.length + j
                      return (
                        <li key={tag.slug ?? tag.name ?? j} role="option" id={`sb-mobile-item-${flatIdx}`} aria-selected={activeIdx === flatIdx}>
                          <button
                            type="button"
                            onClick={() => onNavigate({ type: 'tag', ...tag })}
                            className={`w-full min-h-12 flex items-center gap-3 px-3 py-2 text-left rounded-lg transition-colors ${activeIdx === flatIdx ? 'bg-white/[0.14]' : 'hover:bg-white/[0.08]'}`}
                          >
                            <span className="w-10 h-10 rounded-lg bg-white/[0.04] border border-white/[0.07] inline-flex items-center justify-center shrink-0" aria-hidden="true">
                              <svg className="w-4 h-4 text-white/45" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="2">
                                <path strokeLinecap="round" strokeLinejoin="round" d="M7 20l4-16m2 16l4-16M6 9h14M4 15h14"/>
                              </svg>
                            </span>
                            <div className="min-w-0">
                              <div className="text-sm font-medium text-white truncate">#{tag.name ?? tag.slug}</div>
                              {tag.artworks_count != null && <div className="text-xs text-neutral-400">{tag.artworks_count.toLocaleString()} artworks</div>}
                            </div>
                          </button>
                        </li>
                      )
                    })}
                  </>
                )}

                <li role="presentation" className="px-3 pt-3 pb-2 border-t border-white/[0.06] mt-2">
                  <a href={`/search?q=${encodeURIComponent(query)}`} className="min-h-12 inline-flex items-center gap-1.5 text-sm text-accent hover:text-accent/80 transition-colors">
                    See all results for <span className="font-semibold">"{query}"</span>
                    <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="2">
                      <path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7"/>
                    </svg>
                  </a>
                </li>
              </ul>
            ) : (
              <div className="mx-2 my-2 px-6 py-10 rounded-xl border border-white/[0.10] bg-nova-900/95 backdrop-blur-sm shadow-2xl text-sm text-white/60">
                {query.trim().length >= 2 ? 'No results found.' : 'Start typing to search artworks, groups, creators, and tags.'}
              </div>
            )}
          </div>
        </form>
      </div>
    </div>
  )
}
