'use client'

import { useEffect, useMemo, useState } from 'react'
import { Check, Folder, Plus, X } from 'lucide-react'
import { toast } from 'react-hot-toast'
import { DEFAULT_SUPPLIER_CATEGORIES, normalizeSupplierCategoryName, uniqueSupplierCategories } from '@/lib/supplierCategories'

interface SupplierCategorySelectorProps {
  selectedCategories: string[]
  onChange: (categories: string[]) => void
  availableCategories?: string[]
}

const STORAGE_KEY = 'zerp_supplier_custom_categories'

function readStoredCategories(): string[] {
  if (typeof window === 'undefined') return []
  try {
    const stored = window.localStorage.getItem(STORAGE_KEY)
    return stored ? JSON.parse(stored) : []
  } catch {
    return []
  }
}

function writeStoredCategories(categories: string[]) {
  if (typeof window === 'undefined') return
  window.localStorage.setItem(STORAGE_KEY, JSON.stringify(categories))
}

export default function SupplierCategorySelector({ selectedCategories, onChange, availableCategories = [] }: SupplierCategorySelectorProps) {
  const [searchTerm, setSearchTerm] = useState('')
  const [showAddModal, setShowAddModal] = useState(false)
  const [newCategoryName, setNewCategoryName] = useState('')
  const [storedCategories, setStoredCategories] = useState<string[]>([])

  useEffect(() => {
    setStoredCategories(readStoredCategories())
  }, [])

  const options = useMemo(
    () => uniqueSupplierCategories([
      ...DEFAULT_SUPPLIER_CATEGORIES,
      ...availableCategories,
      ...storedCategories,
      ...selectedCategories,
    ]),
    [availableCategories, selectedCategories, storedCategories],
  )

  const filteredOptions = options.filter((category) =>
    normalizeSupplierCategoryName(category).includes(normalizeSupplierCategoryName(searchTerm)),
  )

  const isSelected = (category: string) =>
    selectedCategories.some((selected) => normalizeSupplierCategoryName(selected) === normalizeSupplierCategoryName(category))

  const toggleCategory = (category: string) => {
    if (isSelected(category)) {
      onChange(selectedCategories.filter((selected) => normalizeSupplierCategoryName(selected) !== normalizeSupplierCategoryName(category)))
      return
    }
    onChange(uniqueSupplierCategories([...selectedCategories, category]))
  }

  const removeCategory = (category: string) => {
    onChange(selectedCategories.filter((selected) => normalizeSupplierCategoryName(selected) !== normalizeSupplierCategoryName(category)))
  }

  const addCategory = () => {
    const label = newCategoryName.trim()
    if (!label) {
      toast.error('اسم التصنيف مطلوب')
      return
    }

    const nextStored = uniqueSupplierCategories([...storedCategories, label])
    setStoredCategories(nextStored)
    writeStoredCategories(nextStored)
    onChange(uniqueSupplierCategories([...selectedCategories, label]))
    setNewCategoryName('')
    setShowAddModal(false)
    toast.success('تمت إضافة التصنيف')
  }

  return (
    <div className="space-y-3">
      <div className="flex gap-2">
        <input
          type="text"
          value={searchTerm}
          onChange={(event) => setSearchTerm(event.target.value)}
          placeholder="Search categories..."
          className="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-emerald-500 bg-white text-gray-900"
        />
        <button type="button" onClick={() => setShowAddModal(true)} className="px-3 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors" title="Add Category">
          <Plus className="h-5 w-5" />
        </button>
      </div>

      {selectedCategories.length > 0 && (
        <div className="flex flex-wrap gap-2 p-3 bg-gray-50 rounded-lg">
          {selectedCategories.map((category) => (
            <span key={category} className="inline-flex items-center gap-2 px-3 py-1 bg-emerald-100 text-emerald-700 rounded-full text-sm">
              {category}
              <button type="button" onClick={() => removeCategory(category)} className="hover:text-emerald-900"><X className="h-3 w-3" /></button>
            </span>
          ))}
        </div>
      )}

      <div className="border border-gray-200 rounded-lg p-3 max-h-96 overflow-y-auto bg-white">
        {filteredOptions.length === 0 ? (
          <div className="text-center py-8 text-gray-500">
            <Folder className="h-12 w-12 mx-auto mb-2 text-gray-300" />
            <p>لا يوجد تصنيفات مطابقة</p>
            <button type="button" onClick={() => setShowAddModal(true)} className="mt-2 text-emerald-600 hover:text-emerald-700 text-sm">إضافة تصنيف جديد</button>
          </div>
        ) : (
          filteredOptions.map((category) => {
            const selected = isSelected(category)
            return (
              <div key={category} className={`flex items-center gap-2 px-3 py-2 rounded-lg cursor-pointer transition-colors ${selected ? 'bg-emerald-50 border border-emerald-200' : 'hover:bg-gray-50'}`} onClick={() => toggleCategory(category)}>
                <div className="w-6" />
                <Folder className="h-4 w-4 text-gray-600" />
                <span className="flex-1 text-sm font-medium text-gray-900 text-right">{category}</span>
                <button
                  type="button"
                  onClick={(event) => { event.stopPropagation(); toggleCategory(category) }}
                  className={`w-5 h-5 rounded border-2 flex items-center justify-center cursor-pointer transition-colors ${selected ? 'bg-emerald-600 border-emerald-600' : 'border-gray-300 bg-white hover:border-emerald-400'}`}
                >
                  {selected && <Check className="h-3 w-3 text-white" />}
                </button>
              </div>
            )
          })
        )}
      </div>

      {showAddModal && (
        <div className="fixed inset-0 z-50 overflow-y-auto">
          <div className="fixed inset-0 bg-black bg-opacity-50" onClick={() => setShowAddModal(false)} />
          <div className="flex min-h-screen items-center justify-center p-4">
            <div className="relative bg-white rounded-xl shadow-2xl p-6 max-w-md w-full">
              <h3 className="text-lg font-bold text-gray-900 mb-4">إضافة تصنيف مورد</h3>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">اسم التصنيف <span className="text-red-500">*</span></label>
                <input
                  type="text"
                  value={newCategoryName}
                  onChange={(event) => setNewCategoryName(event.target.value)}
                  onKeyDown={(event) => { if (event.key === 'Enter') { event.preventDefault(); addCategory() } }}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-emerald-500 bg-white text-gray-900"
                  placeholder="مثال: أجهزة طباعة"
                  autoFocus
                />
              </div>
              <div className="flex items-center justify-end gap-3 mt-6">
                <button type="button" onClick={() => { setShowAddModal(false); setNewCategoryName('') }} className="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50">إلغاء</button>
                <button type="button" onClick={addCategory} className="px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700">إضافة</button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
