'use client'

import { useState, useEffect } from 'react'
import { ChevronRight, ChevronDown, Plus, Check, Folder, FolderOpen, X } from 'lucide-react'
import { categoriesAPI, Category } from '@/lib/api/categories'
import { filterContactCategoryTree } from '@/lib/supplierCategories'
import { toast } from 'react-hot-toast'

interface CategorySelectorProps {
  selectedIds: string[]
  onChange: (selectedIds: string[]) => void
  multiSelect?: boolean
  categoryFilter?: (category: Category) => boolean
}

export default function CategorySelector({ selectedIds, onChange, multiSelect = true, categoryFilter }: CategorySelectorProps) {
  const [categories, setCategories] = useState<Category[]>([])
  const [loading, setLoading] = useState(true)
  const [expandedIds, setExpandedIds] = useState<Set<string>>(new Set())
  const [showAddModal, setShowAddModal] = useState(false)
  const [newCategoryName, setNewCategoryName] = useState('')
  const [newCategoryNameAr, setNewCategoryNameAr] = useState('')
  const [newCategoryParentId, setNewCategoryParentId] = useState<string | undefined>()
  const [searchTerm, setSearchTerm] = useState('')

  useEffect(() => {
    fetchCategories()
  }, [])

  const filterCategoryTree = (items: Category[]): Category[] => {
    if (!categoryFilter) return items

    return items
      .map((category) => {
        const children = category.children ? filterCategoryTree(category.children) : []
        const shouldShow = categoryFilter(category)

        if (!shouldShow && children.length === 0) return null

        return { ...category, children } as Category
      })
      .filter(Boolean) as Category[]
  }

  const visibleCategories = filterCategoryTree(categories)

  const fetchCategories = async () => {
    setLoading(true)
    try {
      const data = await categoriesAPI.getTree()
      setCategories(filterContactCategoryTree(data))
    } catch (error) {
      toast.error('Failed to load categories')
    } finally {
      setLoading(false)
    }
  }

  const toggleExpand = (id: string) => {
    const newExpanded = new Set(expandedIds)
    if (newExpanded.has(id)) {
      newExpanded.delete(id)
    } else {
      newExpanded.add(id)
    }
    setExpandedIds(newExpanded)
  }

  const toggleSelect = (id: string) => {
    if (multiSelect) {
      const newSelected = selectedIds.includes(id)
        ? selectedIds.filter(sid => sid !== id)
        : [...selectedIds, id]
      onChange(newSelected)
    } else {
      onChange([id])
    }
  }

  const handleAddCategory = async () => {
    if (!newCategoryName.trim()) {
      toast.error('Category name is required')
      return
    }

    try {
      await categoriesAPI.create({
        name: newCategoryName,
        nameAr: newCategoryNameAr || undefined,
        parentId: newCategoryParentId
      })
      toast.success('Category created successfully')
      setNewCategoryName('')
      setNewCategoryNameAr('')
      setNewCategoryParentId(undefined)
      setShowAddModal(false)
      fetchCategories()
    } catch (error: any) {
      toast.error(error.response?.data?.message || 'Failed to create category')
    }
  }

  const renderCategory = (category: Category, level: number = 0) => {
    const isSelected = selectedIds.includes(category.id)
    const isExpanded = expandedIds.has(category.id)
    const hasChildren = category.children && category.children.length > 0
    const matchesSearch = searchTerm === '' || 
      category.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      (category.nameAr && category.nameAr.includes(searchTerm))

    if (!matchesSearch && searchTerm !== '') return null

    return (
      <div key={category.id}>
        <div
          className={`flex items-center gap-2 px-3 py-2 rounded-lg cursor-pointer transition-colors ${
            isSelected ? 'bg-blue-50 border border-blue-200' : 'hover:bg-gray-50'
          }`}
          style={{ paddingLeft: `${level * 1.5 + 0.75}rem` }}
        >
          {/* Expand/Collapse */}
          {hasChildren ? (
            <button
              type="button"
              onClick={(e) => {
                e.stopPropagation()
                toggleExpand(category.id)
              }}
              className="p-1 hover:bg-gray-200 rounded"
            >
              {isExpanded ? (
                <ChevronDown className="h-4 w-4 text-gray-600" />
              ) : (
                <ChevronRight className="h-4 w-4 text-gray-600" />
              )}
            </button>
          ) : (
            <div className="w-6" />
          )}

          {/* Folder Icon */}
          {isExpanded ? (
            <FolderOpen className="h-4 w-4 text-blue-600" />
          ) : (
            <Folder className="h-4 w-4 text-gray-600" />
          )}

          {/* Category Name */}
          <button
            type="button"
            onClick={() => toggleSelect(category.id)}
            className="flex-1 text-left flex items-center gap-2"
          >
            <span className="text-sm font-medium text-gray-900">{category.name}</span>
            {category.nameAr && (
              <span className="text-xs text-gray-500" dir="rtl">({category.nameAr})</span>
            )}
            {category._count && category._count.contacts > 0 && (
              <span className="text-xs text-gray-400">({category._count.contacts})</span>
            )}
          </button>

          {/* Selection Checkbox */}
          <button
            type="button"
            onClick={(e) => {
              e.stopPropagation()
              toggleSelect(category.id)
            }}
            className={`w-5 h-5 rounded border-2 flex items-center justify-center cursor-pointer transition-colors ${
              isSelected
                ? 'bg-blue-600 border-blue-600'
                : 'border-gray-300 bg-white hover:border-blue-400'
            }`}
          >
            {isSelected && <Check className="h-3 w-3 text-white" />}
          </button>
        </div>

        {/* Children */}
        {hasChildren && isExpanded && (
          <div>
            {category.children!.map(child => renderCategory(child, level + 1))}
          </div>
        )}
      </div>
    )
  }

  const getSelectedCategories = (): Category[] => {
    const findCategory = (cats: Category[], id: string): Category | null => {
      for (const cat of cats) {
        if (cat.id === id) return cat
        if (cat.children) {
          const found = findCategory(cat.children, id)
          if (found) return found
        }
      }
      return null
    }

    return selectedIds
      .map(id => findCategory(visibleCategories, id))
      .filter(cat => cat !== null) as Category[]
  }

  const removeSelected = (id: string) => {
    onChange(selectedIds.filter(sid => sid !== id))
  }

  if (loading) {
    return <div className="text-center py-4 text-gray-500">Loading categories...</div>
  }

  return (
    <div className="space-y-3">
      {/* Search and Add */}
      <div className="flex gap-2">
        <input
          type="text"
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.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-blue-500 bg-white text-gray-900"
        />
        <button
          type="button"
          onClick={() => setShowAddModal(true)}
          className="px-3 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          title="Add Category"
        >
          <Plus className="h-5 w-5" />
        </button>
      </div>

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

      {/* Category Tree */}
      <div className="border border-gray-200 rounded-lg p-3 max-h-96 overflow-y-auto bg-white">
        {visibleCategories.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>No categories found</p>
            <button
              type="button"
              onClick={() => setShowAddModal(true)}
              className="mt-2 text-blue-600 hover:text-blue-700 text-sm"
            >
              Create your first category
            </button>
          </div>
        ) : (
          visibleCategories.map(category => renderCategory(category))
        )}
      </div>

      {/* Add Category Modal */}
      {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">Add Category</h3>
              
              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Category Name <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="text"
                    value={newCategoryName}
                    onChange={(e) => setNewCategoryName(e.target.value)}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white text-gray-900"
                    placeholder="Enter category name"
                    autoFocus
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Arabic Name
                  </label>
                  <input
                    type="text"
                    value={newCategoryNameAr}
                    onChange={(e) => setNewCategoryNameAr(e.target.value)}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white text-gray-900"
                    placeholder="الاسم بالعربية"
                    dir="rtl"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Parent Category (Optional)
                  </label>
                  <select
                    value={newCategoryParentId || ''}
                    onChange={(e) => setNewCategoryParentId(e.target.value || undefined)}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white text-gray-900"
                  >
                    <option value="">None (Root Category)</option>
                    {visibleCategories.map(cat => (
                      <option key={cat.id} value={cat.id}>{cat.name}</option>
                    ))}
                  </select>
                </div>
              </div>

              <div className="flex items-center justify-end gap-3 mt-6">
                <button
                  type="button"
                  onClick={() => {
                    setShowAddModal(false)
                    setNewCategoryName('')
                    setNewCategoryNameAr('')
                    setNewCategoryParentId(undefined)
                  }}
                  className="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50"
                >
                  Cancel
                </button>
                <button
                  type="button"
                  onClick={handleAddCategory}
                  className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
                >
                  Add Category
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
