import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { SearchIcon } from '../components/icons'
import EmployeeCard from '../components/EmployeeCard'
import { employeeApi } from '../services/api'
import { useAuthStore } from '../stores/authStore'
import type { Employee } from '@skillmate/shared'
import { usePermissions } from '../hooks/usePermissions'

export default function EmployeeList() {
  const navigate = useNavigate()
  const { user } = useAuthStore()
  const { canCreateEmployee } = usePermissions()
  const [employees, setEmployees] = useState<Employee[]>([])
  const [searchTerm, setSearchTerm] = useState('')
  const [filteredEmployees, setFilteredEmployees] = useState<Employee[]>([])
  const [filters, setFilters] = useState({
    department: '',
    skills: '',
    availability: ''
  })
  const [showFilters, setShowFilters] = useState(false)

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

  const fetchEmployees = async () => {
    try {
      const data = await employeeApi.getAll()
      setEmployees(data)
      setFilteredEmployees(data)
    } catch (error) {
      console.error('Failed to fetch employees:', error)
      // Fallback zu Mock-Daten bei Fehler
      const mockEmployees: Employee[] = [
      {
        id: '1',
        firstName: 'Max',
        lastName: 'Mustermann',
        employeeNumber: 'EMP001',
        position: 'Senior Analyst',
        department: 'Cybercrime',
        email: 'max.mustermann@behörde.de',
        phone: '+49 30 12345-100',
        availability: 'available',
        skills: [],
        languages: [],
        specializations: ['Digitale Forensik', 'Malware-Analyse'],
        createdAt: new Date(),
        updatedAt: new Date(),
        createdBy: 'admin',
      },
      // Add more mock data as needed
    ]
      setEmployees(mockEmployees)
      setFilteredEmployees(mockEmployees)
    }
  }

  useEffect(() => {
    let filtered = employees.filter(emp => {
      // Text search
      const matchesSearch = searchTerm === '' ||
        `${emp.firstName} ${emp.lastName}`.toLowerCase().includes(searchTerm.toLowerCase()) ||
        emp.department.toLowerCase().includes(searchTerm.toLowerCase()) ||
        emp.position.toLowerCase().includes(searchTerm.toLowerCase()) ||
        emp.specializations.some(spec => spec.toLowerCase().includes(searchTerm.toLowerCase()))
      
      // Department filter
      const matchesDepartment = filters.department === '' || emp.department === filters.department
      
      // Availability filter
      const matchesAvailability = filters.availability === '' || emp.availability === filters.availability
      
      // Skills filter (basic - später erweitern)
      const matchesSkills = filters.skills === '' || 
        emp.specializations.some(spec => spec.toLowerCase().includes(filters.skills.toLowerCase()))
      
      return matchesSearch && matchesDepartment && matchesAvailability && matchesSkills
    })
    
    setFilteredEmployees(filtered)
  }, [searchTerm, employees, filters])

  return (
    <div>
      <div className="flex justify-between items-center mb-8">
        <h1 className="text-3xl font-bold text-gray-900 dark:text-white">
          Mitarbeitende & Expertise
        </h1>
        <p className="text-gray-600 dark:text-gray-400 mt-1">
          {filteredEmployees.length} von {employees.length} Mitarbeitenden
        </p>
        {canCreateEmployee() && (
          <button 
            onClick={() => navigate('/employees/new')}
            className="btn-primary"
          >
            Mitarbeitende hinzufügen
          </button>
        )}
      </div>

      {/* Erweiterte Suchleiste */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-4 mb-6">
        <div className="flex gap-4 mb-4">
          <div className="flex-1 relative">
            <input
              type="text"
              placeholder="Suche nach Name, Kompetenzen, Abteilung..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500"
            />
            <SearchIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
          </div>
          <button
            onClick={() => setShowFilters(!showFilters)}
            className="px-4 py-2 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600"
          >
            Filter {showFilters ? 'ausblenden' : 'einblenden'}
          </button>
        </div>
        
        {/* Erweiterte Filter */}
        {showFilters && (
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4 pt-4 border-t border-gray-200 dark:border-gray-700">
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Dienststelle
              </label>
              <select
                value={filters.department}
                onChange={(e) => setFilters(prev => ({ ...prev, department: e.target.value }))}
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
              >
                <option value="">Alle Dienststellen</option>
                <option value="Cybercrime">Cybercrime</option>
                <option value="Staatsschutz">Staatsschutz</option>
                <option value="Kriminalpolizei">Kriminalpolizei</option>
                <option value="IT">IT</option>
                <option value="Verwaltung">Verwaltung</option>
              </select>
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Verfügbarkeit
              </label>
              <select
                value={filters.availability}
                onChange={(e) => setFilters(prev => ({ ...prev, availability: e.target.value }))}
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
              >
                <option value="">Alle</option>
                <option value="available">Verfügbar</option>
                <option value="busy">Beschäftigt</option>
                <option value="away">Abwesend</option>
                <option value="vacation">Urlaub</option>
              </select>
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Kompetenzen
              </label>
              <input
                type="text"
                placeholder="z.B. Forensik, Analyse..."
                value={filters.skills}
                onChange={(e) => setFilters(prev => ({ ...prev, skills: e.target.value }))}
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
              />
            </div>
          </div>
        )}
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {filteredEmployees.map((employee) => (
          <EmployeeCard
            key={employee.id}
            employee={employee}
            onClick={() => navigate(`/employees/${employee.id}`)}
          />
        ))}
      </div>

      {filteredEmployees.length === 0 && (
        <div className="text-center py-12">
          <p className="text-tertiary">Keine Mitarbeitenden gefunden</p>
        </div>
      )}
    </div>
  )
}
