import { useState, useRef, useMemo } from 'react'
import { Users, Plus, X, Trash2, Copy } from 'lucide-react'

interface UsernameListEditorProps {
  value: string[]
  onChange: (usernames: string[]) => void
  label: string
  placeholder?: string
}

export default function UsernameListEditor({ value, onChange, label, placeholder = 'Add username...' }: UsernameListEditorProps) {
  const [input, setInput] = useState('')
  const [showPasteModal, setShowPasteModal] = useState(false)
  const [pasteText, setPasteText] = useState('')
  const inputRef = useRef<HTMLInputElement>(null)

  const sorted = useMemo(() => [...value].sort((a, b) => a.localeCompare(b)), [value])

  const duplicates = useMemo(() => {
    const counts: Record<string, number> = {}
    for (const u of value) {
      counts[u] = (counts[u] || 0) + 1
    }
    return new Set(Object.keys(counts).filter(k => counts[k] > 1))
  }, [value])

  const hasDuplicates = duplicates.size > 0

  const addUsername = (raw: string) => {
    const username = raw.trim().toLowerCase()
    if (!username) return
    onChange([...value, username].sort((a, b) => a.localeCompare(b)))
    setInput('')
    inputRef.current?.focus()
  }

  const removeUsername = (index: number) => {
    // index is into the sorted array — find the actual username and remove first occurrence from value
    const username = sorted[index]
    const idx = value.indexOf(username)
    if (idx !== -1) {
      const next = [...value]
      next.splice(idx, 1)
      onChange(next)
    }
  }

  const removeDuplicates = () => {
    onChange([...new Set(value)])
  }

  const handlePaste = () => {
    const parsed = pasteText
      .split(/[,\n]+/)
      .map(u => u.trim().toLowerCase())
      .filter(u => u)
    if (parsed.length > 0) {
      onChange([...value, ...parsed].sort((a, b) => a.localeCompare(b)))
    }
    setPasteText('')
    setShowPasteModal(false)
  }

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      e.preventDefault()
      addUsername(input)
    }
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-2">
        <label className="flex items-center gap-1.5 text-sm font-medium text-slate-700 dark:text-slate-300">
          <Users className="w-3.5 h-3.5" />
          {label}
          <span className="ml-1 px-1.5 py-0.5 text-[10px] font-semibold bg-slate-200 dark:bg-slate-600 text-slate-600 dark:text-slate-300 rounded-full">
            {value.length}
          </span>
        </label>
        <div className="flex items-center gap-1">
          {hasDuplicates && (
            <button
              type="button"
              onClick={removeDuplicates}
              className="flex items-center gap-1 px-2 py-1 text-[10px] font-medium text-amber-700 dark:text-amber-400 bg-amber-50 dark:bg-amber-900/30 border border-amber-200 dark:border-amber-800 rounded-md hover:bg-amber-100 dark:hover:bg-amber-900/50 transition-colors"
            >
              <Trash2 className="w-3 h-3" />
              Remove Duplicates
            </button>
          )}
          <button
            type="button"
            onClick={() => setShowPasteModal(true)}
            className="flex items-center gap-1 px-2 py-1 text-[10px] font-medium text-slate-600 dark:text-slate-400 bg-slate-100 dark:bg-slate-700 rounded-md hover:bg-slate-200 dark:hover:bg-slate-600 transition-colors"
          >
            <Copy className="w-3 h-3" />
            Paste List
          </button>
        </div>
      </div>

      {/* Add input */}
      <div className="flex gap-2 mb-2">
        <input
          ref={inputRef}
          type="text"
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyDown={handleKeyDown}
          className="flex-1 px-3 py-1.5 text-sm border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          placeholder={placeholder}
        />
        <button
          type="button"
          onClick={() => addUsername(input)}
          disabled={!input.trim()}
          className="px-3 py-1.5 bg-blue-600 hover:bg-blue-700 disabled:bg-slate-300 dark:disabled:bg-slate-600 text-white rounded-lg transition-colors flex items-center gap-1 text-sm"
        >
          <Plus className="w-4 h-4" />
        </button>
      </div>

      {/* Username list */}
      {sorted.length === 0 ? (
        <div className="border-2 border-dashed border-slate-300 dark:border-slate-600 rounded-lg p-4 text-center">
          <p className="text-xs text-slate-400 dark:text-slate-500">No usernames added yet</p>
        </div>
      ) : (
        <div className="border border-slate-200 dark:border-slate-700 rounded-lg overflow-hidden">
          <div className="max-h-48 overflow-y-auto custom-scrollbar">
            {sorted.map((username, i) => (
              <div
                key={`${username}-${i}`}
                className="group flex items-center justify-between px-3 py-1.5 text-sm hover:bg-slate-50 dark:hover:bg-slate-700/50 border-b border-slate-100 dark:border-slate-700/50 last:border-b-0"
              >
                <span className="font-mono text-xs text-slate-800 dark:text-slate-200 flex items-center gap-1.5">
                  {username}
                  {duplicates.has(username) && (
                    <span className="px-1 py-0.5 text-[9px] font-semibold bg-amber-100 dark:bg-amber-900/50 text-amber-700 dark:text-amber-400 rounded">
                      DUP
                    </span>
                  )}
                </span>
                <button
                  type="button"
                  onClick={() => removeUsername(i)}
                  className="opacity-0 group-hover:opacity-100 p-0.5 text-slate-400 hover:text-red-500 transition-all"
                >
                  <X className="w-3.5 h-3.5" />
                </button>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Paste Modal */}
      {showPasteModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClick={() => setShowPasteModal(false)}>
          <div className="bg-white dark:bg-slate-800 rounded-xl shadow-xl p-5 w-full max-w-md mx-4" onClick={e => e.stopPropagation()}>
            <h3 className="text-sm font-semibold text-slate-900 dark:text-slate-100 mb-3">Paste Username List</h3>
            <textarea
              value={pasteText}
              onChange={(e) => setPasteText(e.target.value)}
              className="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100 font-mono text-xs"
              rows={6}
              placeholder="Paste usernames separated by commas or newlines..."
              autoFocus
            />
            <div className="flex justify-end gap-2 mt-3">
              <button
                type="button"
                onClick={() => { setPasteText(''); setShowPasteModal(false) }}
                className="px-3 py-1.5 text-sm text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg transition-colors"
              >
                Cancel
              </button>
              <button
                type="button"
                onClick={handlePaste}
                disabled={!pasteText.trim()}
                className="px-3 py-1.5 text-sm bg-blue-600 hover:bg-blue-700 disabled:bg-slate-300 dark:disabled:bg-slate-600 text-white rounded-lg transition-colors"
              >
                Add Usernames
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
