import React, { useState, useEffect, useCallback } from 'react'
import { Search, Filter, Download, User, MapPin, Briefcase, Globe, Tool, BookOpen, Users } from 'lucide-react'
import { api } from '../services/api'
import { useAuthStore } from '../stores/authStore'
import { useNavigate } from 'react-router-dom'

interface Profile {
  id: string
  name: string
  department?: string
  location?: string
  role?: string
  jobCategory?: string
  jobTitle?: string
  tools?: string[]
  methods?: string[]
  languages?: { code: string; level: string }[]
  updatedAt: string
  consentPublicProfile: boolean
}

interface Facets {
  departments: string[]
  locations: string[]
  jobCategories: string[]
  tools: string[]
  methods: string[]
  languages: { code: string; level: string }[]
}

export default function ProfileSearch() {
  const navigate = useNavigate()
  const { user } = useAuthStore()
  const [searchQuery, setSearchQuery] = useState('')
  const [profiles, setProfiles] = useState<Profile[]>([])
  const [facets, setFacets] = useState<Facets | null>(null)
  const [loading, setLoading] = useState(false)
  const [filters, setFilters] = useState({
    department: '',
    location: '',
    jobCategory: '',
    tools: [] as string[],
    methods: [] as string[],
    language: ''
  })
  const [showFilters, setShowFilters] = useState(false)
  const [page, setPage] = useState(1)
  const [totalResults, setTotalResults] = useState(0)

  // Lade Facetten beim Start
  useEffect(() => {
    loadFacets()
  }, [])

  // Suche bei \u00c4nderungen
  useEffect(() => {
    const delayDebounce = setTimeout(() => {
      searchProfiles()
    }, 300)

    return () => clearTimeout(delayDebounce)
  }, [searchQuery, filters, page])

  const loadFacets = async () => {
    try {
      const response = await api.get('/profiles/facets')
      if (response.data.success) {
        setFacets(response.data.data)
      }
    } catch (error) {
      console.error('Error loading facets:', error)
    }
  }

  const searchProfiles = async () => {
    setLoading(true)
    try {
      const params = new URLSearchParams()
      if (searchQuery) params.append('query', searchQuery)
      if (filters.department) params.append('dept', filters.department)
      if (filters.location) params.append('loc', filters.location)
      if (filters.jobCategory) params.append('jobCat', filters.jobCategory)
      if (filters.tools.length > 0) params.append('tools', filters.tools.join(','))
      if (filters.methods.length > 0) params.append('methods', filters.methods.join(','))
      if (filters.language) params.append('lang', filters.language)
      params.append('page', page.toString())
      params.append('pageSize', '20')

      const response = await api.get(`/profiles?${params.toString()}`)
      if (response.data.success) {
        setProfiles(response.data.data)
        setTotalResults(response.data.meta?.total || 0)
      }
    } catch (error) {
      console.error('Error searching profiles:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleExport = async (format: 'json' | 'csv') => {
    try {
      const response = await api.post('/profiles/export', {
        filter: filters,
        format
      })

      if (format === 'csv') {
        const blob = new Blob([response.data], { type: 'text/csv' })
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = 'profiles.csv'
        a.click()
      } else {
        const blob = new Blob([JSON.stringify(response.data.data, null, 2)], { type: 'application/json' })
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = 'profiles.json'
        a.click()
      }
    } catch (error) {
      console.error('Error exporting profiles:', error)
    }
  }

  const isProfileStale = (updatedAt: string) => {
    const oneYearAgo = new Date()
    oneYearAgo.setFullYear(oneYearAgo.getFullYear() - 1)
    return new Date(updatedAt) < oneYearAgo
  }

  const toggleFilter = (type: 'tools' | 'methods', value: string) => {
    setFilters(prev => ({
      ...prev,
      [type]: prev[type].includes(value)
        ? prev[type].filter(v => v !== value)
        : [...prev[type], value]
    }))
  }

  return (
    <div className="max-w-7xl mx-auto px-4 py-8">
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-gray-900 dark:text-white mb-2">
          Expert:innenverzeichnis
        </h1>
        <p className="text-gray-600 dark:text-gray-400">
          Finden Sie schnell die richtigen Ansprechpartner:innen f\u00fcr Ihre Fragen
        </p>
      </div>

      {/* Suchleiste */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-4 mb-6">
        <div className="flex gap-4">
          <div className="flex-1 relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
            <input
              type="text"
              placeholder="Suche nach Namen, Kompetenzen, Projekten..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(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"
            />
          </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 flex items-center gap-2"
          >
            <Filter className="w-5 h-5" />
            Filter
          </button>
          {(user?.role === 'admin' || user?.role === 'poweruser') && (
            <div className="flex gap-2">
              <button
                onClick={() => handleExport('csv')}
                className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 flex items-center gap-2"
              >
                <Download className="w-5 h-5" />
                CSV
              </button>
              <button
                onClick={() => handleExport('json')}
                className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center gap-2"
              >
                <Download className="w-5 h-5" />
                JSON
              </button>
            </div>
          )}
        </div>

        {/* Filter-Panel */}
        {showFilters && facets && (
          <div className="mt-4 pt-4 border-t border-gray-200 dark:border-gray-700">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              {/* Abteilung */}
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  Abteilung
                </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</option>
                  {facets.departments.map(dept => (
                    <option key={dept} value={dept}>{dept}</option>
                  ))}
                </select>
              </div>

              {/* Standort */}
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  Standort
                </label>
                <select
                  value={filters.location}
                  onChange={(e) => setFilters(prev => ({ ...prev, location: 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>
                  {facets.locations.map(loc => (
                    <option key={loc} value={loc}>{loc}</option>
                  ))}
                </select>
              </div>

              {/* Berufskategorie */}
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  Berufskategorie
                </label>
                <select
                  value={filters.jobCategory}
                  onChange={(e) => setFilters(prev => ({ ...prev, jobCategory: 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>
                  {facets.jobCategories.map(cat => (
                    <option key={cat} value={cat}>{cat}</option>
                  ))}
                </select>
              </div>

              {/* Tools */}
              <div className="md:col-span-3">
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  Tools & Software
                </label>
                <div className="flex flex-wrap gap-2">
                  {facets.tools.slice(0, 20).map(tool => (
                    <button
                      key={tool}
                      onClick={() => toggleFilter('tools', tool)}
                      className={`px-3 py-1 rounded-full text-sm ${
                        filters.tools.includes(tool)
                          ? 'bg-blue-600 text-white'
                          : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
                      }`}
                    >
                      {tool}
                    </button>
                  ))}
                </div>
              </div>

              {/* Methoden */}
              <div className="md:col-span-3">
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  Methoden
                </label>
                <div className="flex flex-wrap gap-2">
                  {facets.methods.slice(0, 20).map(method => (
                    <button
                      key={method}
                      onClick={() => toggleFilter('methods', method)}
                      className={`px-3 py-1 rounded-full text-sm ${
                        filters.methods.includes(method)
                          ? 'bg-blue-600 text-white'
                          : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
                      }`}
                    >
                      {method}
                    </button>
                  ))}
                </div>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Ergebnisse */}
      <div className="space-y-4">
        {loading ? (
          <div className="text-center py-8">
            <div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
          </div>
        ) : profiles.length === 0 ? (
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-8 text-center">
            <p className="text-gray-600 dark:text-gray-400">
              Keine Ergebnisse gefunden. Versuchen Sie es mit anderen Suchbegriffen.
            </p>
          </div>
        ) : (
          profiles.map(profile => (
            <div
              key={profile.id}
              onClick={() => navigate(`/profile/${profile.id}`)}
              className="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 hover:shadow-md transition-shadow cursor-pointer"
            >
              <div className="flex justify-between items-start">
                <div className="flex-1">
                  <div className="flex items-center gap-3 mb-2">
                    <User className="w-10 h-10 text-gray-400 bg-gray-100 dark:bg-gray-700 rounded-full p-2" />
                    <div>
                      <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
                        {profile.name}
                      </h3>
                      <div className="flex items-center gap-4 text-sm text-gray-600 dark:text-gray-400">
                        {profile.role && (
                          <span className="flex items-center gap-1">
                            <Briefcase className="w-4 h-4" />
                            {profile.role}
                          </span>
                        )}
                        {profile.department && (
                          <span className="flex items-center gap-1">
                            <Users className="w-4 h-4" />
                            {profile.department}
                          </span>
                        )}
                        {profile.location && (
                          <span className="flex items-center gap-1">
                            <MapPin className="w-4 h-4" />
                            {profile.location}
                          </span>
                        )}
                      </div>
                    </div>
                  </div>

                  {profile.jobTitle && (
                    <p className="text-sm text-gray-700 dark:text-gray-300 mb-3">
                      {profile.jobTitle}
                      {profile.jobCategory && (
                        <span className="ml-2 px-2 py-1 bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 text-xs rounded">
                          {profile.jobCategory}
                        </span>
                      )}
                    </p>
                  )}

                  <div className="flex flex-wrap gap-2 mb-3">
                    {profile.tools?.slice(0, 5).map(tool => (
                      <span key={tool} className="flex items-center gap-1 px-2 py-1 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 text-xs rounded">
                        <Tool className="w-3 h-3" />
                        {tool}
                      </span>
                    ))}
                    {profile.methods?.slice(0, 3).map(method => (
                      <span key={method} className="flex items-center gap-1 px-2 py-1 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 text-xs rounded">
                        <BookOpen className="w-3 h-3" />
                        {method}
                      </span>
                    ))}
                    {profile.languages?.slice(0, 3).map(lang => (
                      <span key={lang.code} className="flex items-center gap-1 px-2 py-1 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 text-xs rounded">
                        <Globe className="w-3 h-3" />
                        {lang.code}: {lang.level}
                      </span>
                    ))}
                  </div>
                </div>

                <div className="flex flex-col items-end gap-2">
                  {isProfileStale(profile.updatedAt) ? (
                    <span className="px-2 py-1 bg-yellow-100 dark:bg-yellow-900 text-yellow-800 dark:text-yellow-200 text-xs rounded">
                      Veraltet
                    </span>
                  ) : (
                    <span className="px-2 py-1 bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200 text-xs rounded">
                      Aktuell
                    </span>
                  )}
                  {!profile.consentPublicProfile && (
                    <span className="px-2 py-1 bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-200 text-xs rounded">
                      Privat
                    </span>
                  )}
                </div>
              </div>
            </div>
          ))
        )}
      </div>

      {/* Pagination */}
      {totalResults > 20 && (
        <div className="flex justify-center gap-2 mt-8">
          <button
            onClick={() => setPage(prev => Math.max(1, prev - 1))}
            disabled={page === 1}
            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 disabled:opacity-50"
          >
            Zur\u00fcck
          </button>
          <span className="px-4 py-2 text-gray-700 dark:text-gray-300">
            Seite {page} von {Math.ceil(totalResults / 20)}
          </span>
          <button
            onClick={() => setPage(prev => prev + 1)}
            disabled={page >= Math.ceil(totalResults / 20)}
            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 disabled:opacity-50"
          >
            Weiter
          </button>
        </div>
      )}
    </div>
  )
}