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

/**
 * Modal for picking tags to add/remove in bulk.
 *
 * Props:
 *  - open: boolean
 *  - mode: 'add' | 'remove'
 *  - onClose: () => void
 *  - onConfirm: (tagIds: number[]) => void
 */
export default function BulkTagModal({ open, mode = 'add', onClose, onConfirm }) {
  const [query, setQuery] = useState('')
  const [results, setResults] = useState([])
  const [selected, setSelected] = useState([]) // { id, name }
  const [loading, setLoading] = useState(false)
  const inputRef = useRef(null)
  const searchTimer = useRef(null)

  // Focus input when modal opens
  useEffect(() => {
    if (open) {
      setQuery('')
      setResults([])
      setSelected([])
      setTimeout(() => inputRef.current?.focus(), 100)
    }
  }, [open])

  // Debounced tag search
  const searchTags = useCallback(async (q) => {
    setLoading(true)
    try {
      const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || ''
      const params = new URLSearchParams()
      if (q) params.set('q', q)
      const res = await fetch(`/api/studio/tags/search?${params.toString()}`, {
        headers: { Accept: 'application/json', 'X-CSRF-TOKEN': csrfToken },
        credentials: 'same-origin',
      })
      const data = await res.json()
      setResults(data || [])
    } catch {
      setResults([])
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    if (!open) return
    clearTimeout(searchTimer.current)
    searchTimer.current = setTimeout(() => searchTags(query), 250)
    return () => clearTimeout(searchTimer.current)
  }, [query, open, searchTags])

  const toggleTag = (tag) => {
    setSelected((prev) => {
      const exists = prev.find((t) => t.id === tag.id)
      return exists ? prev.filter((t) => t.id !== tag.id) : [...prev, { id: tag.id, name: tag.name }]
    })
  }

  const removeSelected = (id) => {
    setSelected((prev) => prev.filter((t) => t.id !== id))
  }

  const handleConfirm = () => {
    if (selected.length === 0) return
    onConfirm(selected.map((t) => t.id))
  }

  const handleKeyDown = (e) => {
    if (e.key === 'Escape') onClose()
  }

  if (!open) return null

  const isAdd = mode === 'add'
  const title = isAdd ? 'Add tags' : 'Remove tags'
  const accentColor = isAdd ? 'accent' : 'amber-500'
  const icon = isAdd ? 'fa-tag' : 'fa-tags'

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

      {/* Modal */}
      <div className="relative w-full max-w-lg bg-nova-900 border border-white/10 rounded-2xl shadow-2xl p-6 space-y-4">
        {/* Header */}
        <div className="flex items-center gap-3">
          <div className={`w-10 h-10 rounded-full ${isAdd ? 'bg-accent/20' : 'bg-amber-500/20'} flex items-center justify-center flex-shrink-0`}>
            <i className={`fa-solid ${icon} ${isAdd ? 'text-accent' : 'text-amber-400'}`} />
          </div>
          <div>
            <h3 className="text-lg font-bold text-white">{title}</h3>
            <p className="text-sm text-slate-400">
              {isAdd ? 'Search and select tags to add to the selected artworks.' : 'Search and select tags to remove from the selected artworks.'}
            </p>
          </div>
        </div>

        {/* Search input */}
        <div className="relative">
          <i className="fa-solid fa-magnifying-glass absolute left-3 top-1/2 -translate-y-1/2 text-slate-500 text-sm pointer-events-none" />
          <input
            ref={inputRef}
            type="text"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            className="w-full py-2.5 rounded-xl bg-white/5 border border-white/10 text-white text-sm focus:outline-none focus:ring-2 focus:ring-accent/50"
            style={{ paddingLeft: '2.5rem' }}
            placeholder="Search tags…"
          />
        </div>

        {/* Selected tags chips */}
        {selected.length > 0 && (
          <div className="flex flex-wrap gap-1.5">
            {selected.map((tag) => (
              <span
                key={tag.id}
                className={`inline-flex items-center gap-1 px-2.5 py-1 rounded-lg text-xs font-medium ${
                  isAdd ? 'bg-accent/20 text-accent' : 'bg-amber-500/20 text-amber-300'
                }`}
              >
                {tag.name}
                <button
                  onClick={() => removeSelected(tag.id)}
                  className="ml-0.5 w-4 h-4 rounded-full hover:bg-white/10 flex items-center justify-center"
                >
                  <i className="fa-solid fa-xmark text-[10px]" />
                </button>
              </span>
            ))}
          </div>
        )}

        {/* Results list */}
        <div className="max-h-48 overflow-y-auto space-y-0.5 rounded-xl bg-white/[0.02] border border-white/5 p-1">
          {loading && (
            <div className="flex items-center justify-center py-4">
              <div className="w-5 h-5 border-2 border-accent/30 border-t-accent rounded-full animate-spin" />
            </div>
          )}

          {!loading && results.length === 0 && (
            <p className="text-center text-sm text-slate-500 py-4">
              {query ? 'No tags found' : 'Type to search tags'}
            </p>
          )}

          {!loading &&
            results.map((tag) => {
              const isSelected = selected.some((t) => t.id === tag.id)
              const recentClicks = Number(tag.recent_clicks || 0)
              const usageCount = Number(tag.usage_count || 0)
              return (
                <button
                  key={tag.id}
                  onClick={() => toggleTag(tag)}
                  className={`w-full flex items-center justify-between px-3 py-2 rounded-lg text-sm transition-all ${
                    isSelected
                      ? isAdd
                        ? 'bg-accent/10 text-accent'
                        : 'bg-amber-500/10 text-amber-300'
                      : 'text-slate-300 hover:bg-white/5 hover:text-white'
                  }`}
                >
                  <span className="flex items-center gap-2">
                    <i
                      className={`fa-${isSelected ? 'solid fa-circle-check' : 'regular fa-circle'} text-xs ${
                        isSelected ? (isAdd ? 'text-accent' : 'text-amber-400') : 'text-slate-500'
                      }`}
                    />
                    {tag.name}
                  </span>
                  <span className="text-xs text-slate-500">
                    {recentClicks > 0 ? `${recentClicks.toLocaleString()} recent clicks` : `${usageCount.toLocaleString()} uses`}
                  </span>
                </button>
              )
            })}
        </div>

        {/* Actions */}
        <div className="flex items-center justify-end gap-2 pt-2">
          <button
            onClick={onClose}
            className="px-4 py-2 rounded-xl text-sm text-slate-400 hover:text-white hover:bg-white/5 transition-all"
          >
            Cancel
          </button>
          <button
            onClick={handleConfirm}
            disabled={selected.length === 0}
            className={`px-5 py-2 rounded-xl text-sm font-semibold transition-all ${
              selected.length > 0
                ? isAdd
                  ? 'bg-accent hover:bg-accent/90 text-white'
                  : 'bg-amber-600 hover:bg-amber-700 text-white'
                : 'bg-white/5 text-slate-500 cursor-not-allowed'
            }`}
          >
            {isAdd ? 'Add' : 'Remove'} {selected.length > 0 ? `${selected.length} tag${selected.length !== 1 ? 's' : ''}` : 'tags'}
          </button>
        </div>
      </div>
    </div>
  )
}
