import { useEffect, useState } from 'react'
import type { OrganizationalUnit } from '@skillmate/shared'
import api from '../services/api'
import { ChevronRight, Building2, Search, X } from 'lucide-react'

interface OrganizationSelectorProps {
  value?: string
  onChange: (unitId: string | null, unitName: string) => void
  disabled?: boolean
}

export default function OrganizationSelector({ value, onChange, disabled }: OrganizationSelectorProps) {
  const [showModal, setShowModal] = useState(false)
  const [hierarchy, setHierarchy] = useState<OrganizationalUnit[]>([])
  const [selectedUnit, setSelectedUnit] = useState<OrganizationalUnit | null>(null)
  const [currentUnitName, setCurrentUnitName] = useState<string>('')
  const [searchTerm, setSearchTerm] = useState('')
  const [expandedNodes, setExpandedNodes] = useState<Set<string>>(new Set())
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    if (showModal) {
      loadOrganization()
    }
  }, [showModal])

  useEffect(() => {
    // Load current unit name if value exists
    if (value && hierarchy.length > 0) {
      const unit = findUnitById(hierarchy, value)
      if (unit) {
        setCurrentUnitName(getUnitPath(hierarchy, unit))
        setSelectedUnit(unit)
      }
    }
  }, [value, hierarchy])

  const loadOrganization = async () => {
    setLoading(true)
    try {
      const response = await api.get('/organization/hierarchy')
      if (response.data.success) {
        setHierarchy(response.data.data)
        // Auto-expand first two levels
        const toExpand = new Set<string>()
        const addFirstLevels = (units: any[], level = 0) => {
          if (level < 2) {
            units.forEach(u => {
              toExpand.add(u.id)
              if (u.children) addFirstLevels(u.children, level + 1)
            })
          }
        }
        addFirstLevels(response.data.data)
        setExpandedNodes(toExpand)
      }
    } catch (error) {
      console.error('Failed to load organization:', error)
    } finally {
      setLoading(false)
    }
  }

  const findUnitById = (units: OrganizationalUnit[], id: string): OrganizationalUnit | null => {
    for (const unit of units) {
      if (unit.id === id) return unit
      if (unit.children) {
        const found = findUnitById(unit.children, id)
        if (found) return found
      }
    }
    return null
  }

  const getUnitPath = (units: OrganizationalUnit[], target: OrganizationalUnit): string => {
    const path: string[] = []
    
    const findPath = (units: OrganizationalUnit[], current: string[] = []): boolean => {
      for (const unit of units) {
        const newPath = [...current, unit.name]
        if (unit.id === target.id) {
          path.push(...newPath)
          return true
        }
        if (unit.children && findPath(unit.children, newPath)) {
          return true
        }
      }
      return false
    }
    
    findPath(units)
    return path.join(' → ')
  }

  const toggleExpand = (unitId: string) => {
    setExpandedNodes(prev => {
      const newSet = new Set(prev)
      if (newSet.has(unitId)) {
        newSet.delete(unitId)
      } else {
        newSet.add(unitId)
      }
      return newSet
    })
  }

  const handleSelect = (unit: OrganizationalUnit) => {
    setSelectedUnit(unit)
    const path = getUnitPath(hierarchy, unit)
    setCurrentUnitName(path)
    onChange(unit.id, path)
    setShowModal(false)
  }

  const getTypeColor = (type: string) => {
    const colors: Record<string, string> = {
      direktion: 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200',
      abteilung: 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200',
      dezernat: 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200',
      sachgebiet: 'bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200',
      teildezernat: 'bg-pink-100 text-pink-800 dark:bg-pink-900 dark:text-pink-200',
      stabsstelle: 'bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200',
      sondereinheit: 'bg-teal-100 text-teal-800 dark:bg-teal-900 dark:text-teal-200'
    }
    return colors[type] || 'bg-gray-100 text-gray-800'
  }

  const matchesSearch = (unit: OrganizationalUnit): boolean => {
    if (!searchTerm) return true
    const term = searchTerm.toLowerCase()
    return unit.name.toLowerCase().includes(term) || 
           unit.code?.toLowerCase().includes(term) || false
  }

  const renderUnit = (unit: OrganizationalUnit, level = 0) => {
    const hasChildren = unit.children && unit.children.length > 0
    const isExpanded = expandedNodes.has(unit.id)
    const matches = matchesSearch(unit)
    
    // Check if any children match
    const hasMatchingChildren = hasChildren && unit.children!.some(child => 
      matchesSearch(child) || (child.children && child.children.some(matchesSearch))
    )
    
    if (!matches && !hasMatchingChildren) return null

    return (
      <div key={unit.id} className={level > 0 ? 'ml-4' : ''}>
        <div
          className={`flex items-center gap-2 p-2 rounded hover:bg-gray-100 dark:hover:bg-gray-700 cursor-pointer ${
            selectedUnit?.id === unit.id ? 'bg-blue-50 dark:bg-blue-900/20' : ''
          }`}
          onClick={() => handleSelect(unit)}
        >
          {hasChildren && (
            <button
              onClick={(e) => {
                e.stopPropagation()
                toggleExpand(unit.id)
              }}
              className="p-0.5 hover:bg-gray-200 dark:hover:bg-gray-600 rounded"
            >
              <ChevronRight 
                className={`w-4 h-4 transition-transform ${isExpanded ? 'rotate-90' : ''}`}
              />
            </button>
          )}
          {!hasChildren && <div className="w-5" />}
          
          <div className="flex-1 flex items-center gap-2">
            <span className={`px-2 py-0.5 text-xs rounded ${getTypeColor(unit.type)}`}>
              {unit.code || unit.type}
            </span>
            <span className="text-sm dark:text-white">{unit.name}</span>
          </div>
        </div>
        
        {hasChildren && isExpanded && (
          <div className="border-l border-gray-200 dark:border-gray-700 ml-2">
            {unit.children!.map(child => renderUnit(child, level + 1))}
          </div>
        )}
      </div>
    )
  }

  return (
    <>
      <div className="relative">
        <input
          type="text"
          className="input-field w-full pr-10"
          value={currentUnitName}
          placeholder="Klicken zum Auswählen..."
          readOnly
          disabled={disabled}
          onClick={() => !disabled && setShowModal(true)}
        />
        <button
          type="button"
          className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
          onClick={() => !disabled && setShowModal(true)}
          disabled={disabled}
        >
          <Building2 className="w-5 h-5" />
        </button>
      </div>

      {showModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-3xl w-full max-h-[80vh] flex flex-col">
            {/* Header */}
            <div className="p-4 border-b border-gray-200 dark:border-gray-700">
              <div className="flex items-center justify-between mb-3">
                <h2 className="text-lg font-semibold dark:text-white">Organisationseinheit auswählen</h2>
                <button
                  onClick={() => setShowModal(false)}
                  className="p-1 hover:bg-gray-100 dark:hover:bg-gray-700 rounded"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>
              
              {/* Search */}
              <div className="relative">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                <input
                  type="text"
                  placeholder="Suche nach Name oder Code..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="w-full pl-10 pr-3 py-2 border rounded dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                />
              </div>
            </div>

            {/* Tree View */}
            <div className="flex-1 overflow-y-auto p-4">
              {loading ? (
                <div className="text-center text-gray-500 dark:text-gray-400">
                  Lade Organisationsstruktur...
                </div>
              ) : hierarchy.length === 0 ? (
                <div className="text-center text-gray-500 dark:text-gray-400">
                  Keine Organisationseinheiten vorhanden
                </div>
              ) : (
                <div className="space-y-1">
                  {hierarchy.map(unit => renderUnit(unit))}
                </div>
              )}
            </div>

            {/* Footer */}
            <div className="p-4 border-t border-gray-200 dark:border-gray-700 flex justify-between">
              <button
                onClick={() => {
                  setSelectedUnit(null)
                  setCurrentUnitName('')
                  onChange(null, '')
                  setShowModal(false)
                }}
                className="px-4 py-2 text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200"
              >
                Auswahl entfernen
              </button>
              <button
                onClick={() => setShowModal(false)}
                className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
              >
                Schließen
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  )
}
