import { useEffect, useState, useCallback } from 'react'
import type { OrganizationalUnit, EmployeeUnitAssignment } from '@skillmate/shared'
import api from '../services/api'
import { useAuthStore } from '../stores/authStore'

interface OrganizationChartProps {
  onClose: () => void
}

export default function OrganizationChart({ onClose }: OrganizationChartProps) {
  const [units, setUnits] = useState<OrganizationalUnit[]>([])
  const [hierarchy, setHierarchy] = useState<any[]>([])
  const [selectedUnit, setSelectedUnit] = useState<OrganizationalUnit | null>(null)
  const [unitEmployees, setUnitEmployees] = useState<any[]>([])
  const [myUnits, setMyUnits] = useState<any[]>([])
  const [searchTerm, setSearchTerm] = useState('')
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [message, setMessage] = useState<string>('')
  const [zoomLevel, setZoomLevel] = useState(1)
  const [panPosition, setPanPosition] = useState({ x: 0, y: 0 })
  const [isDragging, setIsDragging] = useState(false)
  const [dragStart, setDragStart] = useState({ x: 0, y: 0 })
  const { user } = useAuthStore()

  useEffect(() => {
    loadOrganization()
    loadMyUnits()
  }, [])

  const loadOrganization = async () => {
    try {
      const response = await api.get('/organization/hierarchy')
      if (response.data.success) {
        setHierarchy(response.data.data)
      }
    } catch (error) {
      console.error('Failed to load organization:', error)
    } finally {
      setLoading(false)
    }
  }

  const loadMyUnits = async () => {
    try {
      const response = await api.get('/organization/my-units')
      if (response.data.success) {
        setMyUnits(response.data.data)
      }
    } catch (error) {
      console.error('Failed to load my units:', error)
    }
  }

  const loadUnitDetails = async (unitId: string) => {
    try {
      const response = await api.get(`/organization/units/${unitId}`)
      if (response.data.success) {
        setSelectedUnit(response.data.data)
        setUnitEmployees(response.data.data.employees || [])
      }
    } catch (error) {
      console.error('Failed to load unit details:', error)
    }
  }

  const assignMeToSelectedUnit = async () => {
    if (!selectedUnit || !user?.employeeId) return
    setSaving(true)
    setMessage('')
    try {
      await api.post('/organization/assignments', {
        employeeId: user.employeeId,
        unitId: selectedUnit.id,
        role: 'mitarbeiter',
        isPrimary: true
      })
      setMessage('Position erfolgreich gesetzt.')
      await loadMyUnits()
      await loadUnitDetails(selectedUnit.id)
    } catch (error: any) {
      const msg = error?.response?.data?.error?.message || 'Zuweisung fehlgeschlagen'
      setMessage(`Fehler: ${msg}`)
    } finally {
      setSaving(false)
      setTimeout(() => setMessage(''), 3000)
    }
  }

  const getTypeIcon = (type: string) => {
    const icons: Record<string, string> = {
      direktion: '🏛️',
      abteilung: '🏢',
      dezernat: '📁',
      sachgebiet: '📋',
      teildezernat: '🔧',
      fuehrungsstelle: '⭐',
      stabsstelle: '🎯',
      sondereinheit: '🛡️'
    }
    return icons[type] || '📄'
  }

  const getUnitColor = (level: number) => {
    const colors = [
      'bg-gradient-to-r from-purple-500 to-purple-700',
      'bg-gradient-to-r from-pink-500 to-pink-700',
      'bg-gradient-to-r from-blue-500 to-blue-700',
      'bg-gradient-to-r from-green-500 to-green-700',
      'bg-gradient-to-r from-orange-500 to-orange-700',
      'bg-gradient-to-r from-teal-500 to-teal-700'
    ]
    return colors[level % colors.length]
  }

  const handleUnitClick = (unit: OrganizationalUnit) => {
    setSelectedUnit(unit)
    loadUnitDetails(unit.id)
  }

  const handleZoomIn = () => setZoomLevel(prev => Math.min(prev + 0.2, 3))
  const handleZoomOut = () => setZoomLevel(prev => Math.max(prev - 0.2, 0.3))
  const handleResetView = () => {
    setZoomLevel(1)
    setPanPosition({ x: 0, y: 0 })
  }

  const handleMouseDown = (e: React.MouseEvent) => {
    if (e.button === 0) { // Left click only
      setIsDragging(true)
      setDragStart({ x: e.clientX - panPosition.x, y: e.clientY - panPosition.y })
    }
  }

  const handleMouseMove = (e: React.MouseEvent) => {
    if (isDragging) {
      setPanPosition({
        x: e.clientX - dragStart.x,
        y: e.clientY - dragStart.y
      })
    }
  }

  const handleMouseUp = () => {
    setIsDragging(false)
  }

  const renderUnit = (unit: any, level: number = 0) => {
    const isMyUnit = myUnits.some(u => u.id === unit.id)
    const isSearchMatch = searchTerm && unit.name.toLowerCase().includes(searchTerm.toLowerCase())
    
    return (
      <div key={unit.id} className="flex flex-col items-center">
        <div
          onClick={() => handleUnitClick(unit)}
          className={`
            cursor-pointer transform transition-all duration-200 hover:scale-105
            ${isMyUnit ? 'ring-4 ring-yellow-400' : ''}
            ${isSearchMatch ? 'ring-4 ring-blue-400 animate-pulse' : ''}
          `}
        >
          <div className={`rounded-lg shadow-lg overflow-hidden bg-white dark:bg-gray-800 min-w-[200px] max-w-[250px]`}>
            <div className={`p-2 text-white ${getUnitColor(level)}`}>
              <div className="flex items-center justify-between">
                <span className="text-lg">{getTypeIcon(unit.type)}</span>
                {unit.code && <span className="text-xs opacity-90">{unit.code}</span>}
              </div>
            </div>
            <div className="p-3">
              <h4 className="font-semibold text-sm dark:text-white">{unit.name}</h4>
              {unit.hasFuehrungsstelle && (
                <span className="inline-block px-2 py-1 mt-1 text-xs bg-yellow-100 dark:bg-yellow-900 text-yellow-800 dark:text-yellow-200 rounded">
                  FüSt
                </span>
              )}
            </div>
          </div>
        </div>
        
        {unit.children && unit.children.length > 0 && (
          <div className="flex flex-col items-center mt-4">
            <div className="w-px h-8 bg-gray-300 dark:bg-gray-600"></div>
            <div className="flex gap-4">
              {unit.children.map((child: any) => (
                <div key={child.id} className="flex flex-col items-center">
                  <div className="w-px h-4 bg-gray-300 dark:bg-gray-600"></div>
                  {renderUnit(child, level + 1)}
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    )
  }

  if (loading) {
    return (
      <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
        <div className="bg-white dark:bg-gray-800 rounded-lg p-8">
          <div className="text-lg">Lade Organigramm...</div>
        </div>
      </div>
    )
  }

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 z-50 flex">
      {/* Main Modal */}
      <div className="flex-1 bg-white dark:bg-gray-900 flex">
        {/* Left Sidebar */}
        <div className="w-64 bg-gray-50 dark:bg-gray-800 border-r border-gray-200 dark:border-gray-700 p-4 overflow-y-auto">
          <h3 className="font-semibold mb-4 dark:text-white">Navigation</h3>
          
          {/* Search */}
          <div className="mb-4">
            <input
              type="text"
              placeholder="Suche Einheit..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:border-gray-600 dark:text-white"
            />
          </div>

          {/* Quick Links */}
          <div className="space-y-2">
            <button className="w-full text-left px-3 py-2 rounded hover:bg-gray-200 dark:hover:bg-gray-700 dark:text-white">
              📍 Meine Position
            </button>
            <button className="w-full text-left px-3 py-2 rounded hover:bg-gray-200 dark:hover:bg-gray-700 dark:text-white">
              👥 Führungsebene
            </button>
            <button className="w-full text-left px-3 py-2 rounded hover:bg-gray-200 dark:hover:bg-gray-700 dark:text-white">
              🎖️ Beauftragte
            </button>
          </div>

          {/* Department Filters */}
          <h4 className="font-semibold mt-6 mb-2 dark:text-white">Abteilungen</h4>
          <div className="grid grid-cols-2 gap-2">
            {[1, 2, 3, 4, 5, 6].map(n => (
              <button
                key={n}
                className={`px-3 py-2 rounded text-white text-sm ${getUnitColor(n)}`}
              >
                Abt. {n}
              </button>
            ))}
          </div>
        </div>

        {/* Main Chart Area */}
        <div className="flex-1 relative overflow-hidden">
          {/* Header */}
          <div className="absolute top-0 left-0 right-0 bg-white dark:bg-gray-900 border-b border-gray-200 dark:border-gray-700 p-4 z-10">
            <div className="flex items-center justify-between">
              <h2 className="text-xl font-bold dark:text-white">LKA NRW Organigramm</h2>
              <button
                onClick={onClose}
                className="p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded"
              >
                ✕
              </button>
            </div>
          </div>

          {/* Zoom Controls */}
          <div className="absolute top-20 right-4 z-10 flex flex-col gap-2">
            <button
              onClick={handleZoomIn}
              className="p-2 bg-white dark:bg-gray-700 shadow rounded hover:bg-gray-100 dark:hover:bg-gray-600"
            >
              🔍+
            </button>
            <button
              onClick={handleZoomOut}
              className="p-2 bg-white dark:bg-gray-700 shadow rounded hover:bg-gray-100 dark:hover:bg-gray-600"
            >
              🔍-
            </button>
            <button
              onClick={handleResetView}
              className="p-2 bg-white dark:bg-gray-700 shadow rounded hover:bg-gray-100 dark:hover:bg-gray-600"
            >
              🎯
            </button>
          </div>

          {/* Chart Canvas */}
          <div
            className="absolute inset-0 mt-16 overflow-auto cursor-move"
            onMouseDown={handleMouseDown}
            onMouseMove={handleMouseMove}
            onMouseUp={handleMouseUp}
            onMouseLeave={handleMouseUp}
            style={{ cursor: isDragging ? 'grabbing' : 'grab' }}
          >
            <div
              className="p-8"
              style={{
                transform: `scale(${zoomLevel}) translate(${panPosition.x / zoomLevel}px, ${panPosition.y / zoomLevel}px)`,
                transformOrigin: 'center',
                transition: isDragging ? 'none' : 'transform 0.2s'
              }}
            >
              {hierarchy.map(unit => renderUnit(unit))}
            </div>
          </div>
        </div>

        {/* Right Sidebar - Details */}
        {selectedUnit && (
          <div className="w-80 bg-gray-50 dark:bg-gray-800 border-l border-gray-200 dark:border-gray-700 p-4 overflow-y-auto">
            <div className={`p-3 text-white rounded-lg mb-4 ${getUnitColor(selectedUnit.level || 0)}`}>
              <h3 className="text-lg font-semibold">{selectedUnit.name}</h3>
              {selectedUnit.code && <p className="text-sm opacity-90">{selectedUnit.code}</p>}
            </div>

            {/* Tabs */}
            <div className="border-b border-gray-200 dark:border-gray-700 mb-4">
              <div className="flex gap-4">
                <button className="pb-2 border-b-2 border-blue-500 dark:text-white">
              Mitarbeitende
                </button>
                <button className="pb-2 dark:text-gray-400">
                  Skills
                </button>
                <button className="pb-2 dark:text-gray-400">
                  Vertretung
                </button>
              </div>
            </div>

            {/* Employee List */}
            <div className="space-y-2">
              {unitEmployees.map(emp => (
                <div key={emp.id} className="p-3 bg-white dark:bg-gray-700 rounded-lg">
                  <div className="flex items-center gap-3">
                    {emp.photo ? (
                      <img
                        src={`/api${emp.photo}`}
                        alt=""
                        className="w-10 h-10 rounded-full object-cover"
                      />
                    ) : (
                      <div className="w-10 h-10 rounded-full bg-gray-200 dark:bg-gray-600 flex items-center justify-center">
                        👤
                      </div>
                    )}
                    <div>
                      <p className="font-medium dark:text-white">{emp.firstName} {emp.lastName}</p>
                      <p className="text-sm text-gray-600 dark:text-gray-400">
                        {emp.role === 'leiter' && '🔑 Leitung'}
                        {emp.role === 'stellvertreter' && '↔️ Stellvertretung'}
                        {emp.role === 'mitarbeiter' && 'Mitarbeitende Person'}
                        {emp.role === 'beauftragter' && '🎖️ Beauftragter'}
                      </p>
                    </div>
                  </div>
                </div>
              ))}
              {unitEmployees.length === 0 && (
                <p className="text-gray-500 dark:text-gray-400">Keine Mitarbeitenden zugeordnet</p>
              )}
            </div>

            {selectedUnit.description && (
              <div className="mt-4 p-3 bg-blue-50 dark:bg-blue-900/20 rounded">
                <h4 className="font-semibold mb-1 dark:text-white">Beschreibung</h4>
                <p className="text-sm dark:text-gray-300">{selectedUnit.description}</p>
              </div>
            )}

            {user?.employeeId && (
              <div className="mt-4">
                <button
                  onClick={assignMeToSelectedUnit}
                  disabled={saving}
                  className="w-full px-3 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 disabled:opacity-60"
                >
                  {saving ? 'Wird zugeordnet...' : 'In diese Einheit einordnen'}
                </button>
                {message && (
                  <p className="text-sm mt-2 text-gray-700 dark:text-gray-300">{message}</p>
                )}
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  )
}
