import React, { useState, useEffect, useRef, useCallback } from 'react'
import axios from 'axios'

/**
 * TagPeopleModal
 *
 * Props:
 *   isOpen        boolean
 *   onClose       function()
 *   selected      array   [{ id, username, name, avatar_url }]
 *   onConfirm     function(selectedArray)
 */
export default function TagPeopleModal({ isOpen, onClose, selected = [], onConfirm }) {
  const [query,     setQuery]     = useState('')
  const [results,   setResults]   = useState([])
  const [loading,   setLoading]   = useState(false)
  const [staged,    setStaged]    = useState(selected)
  const inputRef    = useRef(null)
  const debounce    = useRef(null)

  // Re-sync staged list when modal opens
  useEffect(() => {
    if (isOpen) {
      setStaged(selected)
      setQuery('')
      setResults([])
      setTimeout(() => inputRef.current?.focus(), 80)
    }
  }, [isOpen])

  const search = useCallback(async (q) => {
    if (q.length < 2) { setResults([]); return }
    setLoading(true)
    try {
      const { data } = await axios.get('/api/search/users', { params: { q, per_page: 8 } })
      setResults(data.data ?? [])
    } catch {
      setResults([])
    } finally {
      setLoading(false)
    }
  }, [])

  const handleQueryChange = (e) => {
    const val = e.target.value
    setQuery(val)
    clearTimeout(debounce.current)
    debounce.current = setTimeout(() => search(val.replace(/^@/, '')), 300)
  }

  const isSelected = (user) => staged.some((u) => u.id === user.id)

  const toggle = (user) => {
    setStaged((prev) =>
      isSelected(user)
        ? prev.filter((u) => u.id !== user.id)
        : prev.length < 10 ? [...prev, user] : prev
    )
  }

  const handleConfirm = () => {
    onConfirm(staged)
    onClose()
  }

  if (!isOpen) return null

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      {/* Backdrop */}
      <div className="absolute inset-0 bg-black/70 backdrop-blur-sm" onClick={onClose} />

      {/* Modal */}
      <div className="relative w-full max-w-md rounded-2xl border border-white/10 bg-[#0c1525] shadow-2xl overflow-hidden flex flex-col max-h-[80vh]">

        {/* Header */}
        <div className="flex items-center gap-3 px-5 py-4 border-b border-white/[0.07]">
          <button
            type="button"
            onClick={onClose}
            className="w-8 h-8 rounded-full hover:bg-white/10 flex items-center justify-center text-slate-400 hover:text-white transition-colors"
            aria-label="Back"
          >
            <i className="fa-solid fa-arrow-left fa-sm" />
          </button>
          <h2 className="flex-1 text-center text-base font-semibold text-white/90 -ml-8">
            Tag people
          </h2>
          <button
            type="button"
            onClick={handleConfirm}
            className="text-sm font-medium text-sky-400 hover:text-sky-300 transition-colors"
          >
            Done
          </button>
        </div>

        {/* Search bar */}
        <div className="px-4 py-3 border-b border-white/[0.05]">
          <div className="flex items-center gap-2 bg-white/[0.06] border border-white/[0.08] rounded-xl px-3 py-2">
            <i className="fa-solid fa-magnifying-glass text-slate-500 text-xs fa-fw" />
            <input
              ref={inputRef}
              type="text"
              value={query}
              onChange={handleQueryChange}
              placeholder="Search users…"
              className="flex-1 bg-transparent text-sm text-white placeholder-slate-600 focus:outline-none"
            />
            {loading && <i className="fa-solid fa-spinner fa-spin text-slate-500 text-xs" />}
            {query && !loading && (
              <button type="button" onClick={() => { setQuery(''); setResults([]) }} className="text-slate-500 hover:text-white">
                <i className="fa-solid fa-xmark text-xs" />
              </button>
            )}
          </div>
        </div>

        {/* Selected chips */}
        {staged.length > 0 && (
          <div className="flex flex-wrap gap-2 px-4 py-3 border-b border-white/[0.05]">
            {staged.map((u) => (
              <span
                key={u.id}
                className="flex items-center gap-1.5 px-2.5 py-1 bg-sky-500/15 border border-sky-500/30 rounded-full text-xs text-sky-400"
              >
                <img
                  src={u.avatar_url ?? '/images/avatar_default.webp'}
                  alt=""
                  className="w-4 h-4 rounded-full object-cover"
                />
                @{u.username}
                <button
                  type="button"
                  onClick={() => toggle(u)}
                  className="ml-0.5 opacity-60 hover:opacity-100 transition-opacity"
                  aria-label={`Remove @${u.username}`}
                >
                  <i className="fa-solid fa-xmark fa-xs" />
                </button>
              </span>
            ))}
          </div>
        )}

        {/* Results list */}
        <div className="overflow-y-auto flex-1">
          {results.length === 0 && query.length >= 2 && !loading && (
            <p className="px-5 py-8 text-center text-sm text-slate-600">No users found for "{query}"</p>
          )}
          {results.length === 0 && query.length < 2 && (
            <p className="px-5 py-8 text-center text-sm text-slate-600">Type a name or @username to search</p>
          )}
          {results.map((u) => {
            const checked = isSelected(u)
            return (
              <button
                key={u.id}
                type="button"
                onClick={() => toggle(u)}
                className={`w-full flex items-center gap-3 px-5 py-3 text-left transition-colors ${
                  checked ? 'bg-sky-500/10' : 'hover:bg-white/[0.04]'
                }`}
              >
                <img
                  src={u.avatar_url ?? '/images/avatar_default.webp'}
                  alt={u.username}
                  className="w-10 h-10 rounded-full object-cover ring-1 ring-white/10 shrink-0"
                  loading="lazy"
                />
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-medium text-white/90 truncate">
                    {u.name || `@${u.username}`}
                  </p>
                  <p className="text-xs text-slate-500 truncate">@{u.username}</p>
                </div>
                <div className={`w-5 h-5 rounded-full border-2 flex items-center justify-center shrink-0 transition-colors ${
                  checked
                    ? 'bg-sky-500 border-sky-500 text-white'
                    : 'border-white/20'
                }`}>
                  {checked && <i className="fa-solid fa-check fa-xs" />}
                </div>
              </button>
            )
          })}
        </div>

        {/* Footer confirm */}
        <div className="px-5 py-3 border-t border-white/[0.07]">
          <button
            type="button"
            onClick={handleConfirm}
            className="w-full py-2.5 rounded-xl bg-sky-600 hover:bg-sky-500 text-white text-sm font-medium transition-colors disabled:opacity-40"
          >
            {staged.length === 0
              ? 'Continue without tagging'
              : `Tag ${staged.length} ${staged.length === 1 ? 'person' : 'people'}`}
          </button>
        </div>
      </div>
    </div>
  )
}
