import React, { useState, useEffect } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { Save, X, Plus, Trash2, AlertCircle, Check } from 'lucide-react'
import { api } from '../services/api'
import { useAuthStore } from '../stores/authStore'

interface ProfileForm {
  name: string
  department: string
  location: string
  role: string
  contacts: {
    email: string
    phone: string
    teams: string
  }
  domains: string[]
  tools: string[]
  methods: string[]
  industryKnowledge: string[]
  regulatory: string[]
  languages: { code: string; level: 'basic' | 'fluent' | 'native' | 'business' }[]
  projects: { title: string; role?: string; summary?: string; links?: string[] }[]
  networks: string[]
  digitalSkills: string[]
  socialSkills: string[]
  jobCategory?: string
  jobTitle?: string
  jobDesc?: string
  consentPublicProfile: boolean
  consentSearchable: boolean
}

const JOB_CATEGORIES = [
  'Technik',
  'IT & Digitalisierung',
  'Verwaltung',
  'F&E',
  'Kommunikation & HR',
  'Produktion',
  'Sonstiges'
]

const LANGUAGE_LEVELS = [
  { value: 'basic', label: 'Grundkenntnisse' },
  { value: 'business', label: 'Verhandlungssicher' },
  { value: 'fluent', label: 'Flie\u00dfend' },
  { value: 'native', label: 'Muttersprache' }
]

export default function ProfileEdit() {
  const { id } = useParams()
  const navigate = useNavigate()
  const { user } = useAuthStore()
  const [loading, setLoading] = useState(false)
  const [saving, setSaving] = useState(false)
  const [showSuccess, setShowSuccess] = useState(false)
  const [errors, setErrors] = useState<string[]>([])
  const [suggestions, setSuggestions] = useState<Record<string, string[]>>({})
  const [activeInput, setActiveInput] = useState<string | null>(null)

  const [formData, setFormData] = useState<ProfileForm>({
    name: '',
    department: '',
    location: '',
    role: '',
    contacts: { email: '', phone: '', teams: '' },
    domains: [],
    tools: [],
    methods: [],
    industryKnowledge: [],
    regulatory: [],
    languages: [],
    projects: [],
    networks: [],
    digitalSkills: [],
    socialSkills: [],
    jobCategory: undefined,
    jobTitle: '',
    jobDesc: '',
    consentPublicProfile: false,
    consentSearchable: false
  })

  useEffect(() => {
    if (id && id !== 'new') {
      loadProfile()
    }
  }, [id])

  const loadProfile = async () => {
    setLoading(true)
    try {
      const response = await api.get(`/profiles/${id}`)
      if (response.data.success) {
        setFormData(response.data.data)
      }
    } catch (error) {
      console.error('Error loading profile:', error)
      setErrors(['Profil konnte nicht geladen werden'])
    } finally {
      setLoading(false)
    }
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setErrors([])
    
    // Validierung
    if (!formData.name) {
      setErrors(['Name ist erforderlich'])
      return
    }

    if (!formData.consentPublicProfile && !formData.consentSearchable) {
      const confirmed = window.confirm(
        'Ihr Profil wird f\u00fcr andere nicht sichtbar sein. M\u00f6chten Sie fortfahren?'
      )
      if (!confirmed) return
    }

    setSaving(true)
    try {
      if (id === 'new') {
        const response = await api.post('/profiles', formData)
        if (response.data.success) {
          setShowSuccess(true)
          setTimeout(() => {
            navigate(`/profile/${response.data.data.id}`)
          }, 1500)
        }
      } else {
        const response = await api.put(`/profiles/${id}`, formData)
        if (response.data.success) {
          setShowSuccess(true)
          setTimeout(() => {
            navigate(`/profile/${id}`)
          }, 1500)
        }
      }
    } catch (error: any) {
      setErrors([error.response?.data?.error?.message || 'Fehler beim Speichern'])
    } finally {
      setSaving(false)
    }
  }

  const loadSuggestions = async (category: string, query: string) => {
    try {
      const response = await api.post('/profiles/tags/suggest', {
        category,
        query
      })
      if (response.data.success) {
        setSuggestions(prev => ({
          ...prev,
          [category]: response.data.data.map((s: any) => s.value)
        }))
      }
    } catch (error) {
      console.error('Error loading suggestions:', error)
    }
  }

  const addToArray = (field: keyof ProfileForm, value: string) => {
    const array = formData[field] as string[]
    if (!array.includes(value)) {
      setFormData(prev => ({
        ...prev,
        [field]: [...array, value]
      }))
    }
  }

  const removeFromArray = (field: keyof ProfileForm, index: number) => {
    const array = formData[field] as string[]
    setFormData(prev => ({
      ...prev,
      [field]: array.filter((_, i) => i !== index)
    }))
  }

  const addLanguage = () => {
    setFormData(prev => ({
      ...prev,
      languages: [...prev.languages, { code: '', level: 'basic' }]
    }))
  }

  const updateLanguage = (index: number, field: 'code' | 'level', value: string) => {
    setFormData(prev => ({
      ...prev,
      languages: prev.languages.map((lang, i) => 
        i === index ? { ...lang, [field]: value } : lang
      )
    }))
  }

  const removeLanguage = (index: number) => {
    setFormData(prev => ({
      ...prev,
      languages: prev.languages.filter((_, i) => i !== index)
    }))
  }

  const addProject = () => {
    setFormData(prev => ({
      ...prev,
      projects: [...prev.projects, { title: '', role: '', summary: '', links: [] }]
    }))
  }

  const updateProject = (index: number, field: string, value: any) => {
    setFormData(prev => ({
      ...prev,
      projects: prev.projects.map((proj, i) => 
        i === index ? { ...proj, [field]: value } : proj
      )
    }))
  }

  const removeProject = (index: number) => {
    setFormData(prev => ({
      ...prev,
      projects: prev.projects.filter((_, i) => i !== index)
    }))
  }

  if (loading) {
    return (
      <div className="flex justify-center items-center h-screen">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
      </div>
    )
  }

  return (
    <div className="max-w-4xl mx-auto px-4 py-8">
      <form onSubmit={handleSubmit} className="space-y-8">
        {/* Header */}
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-4">
            {id === 'new' ? 'Neues Profil erstellen' : 'Profil bearbeiten'}
          </h1>

          {errors.length > 0 && (
            <div className="mb-4 p-4 bg-red-100 dark:bg-red-900 rounded-lg flex items-start gap-2">
              <AlertCircle className="w-5 h-5 text-red-600 dark:text-red-300 mt-0.5" />
              <div>
                {errors.map((error, i) => (
                  <p key={i} className="text-red-600 dark:text-red-300">{error}</p>
                ))}
              </div>
            </div>
          )}

          {showSuccess && (
            <div className="mb-4 p-4 bg-green-100 dark:bg-green-900 rounded-lg flex items-center gap-2">
              <Check className="w-5 h-5 text-green-600 dark:text-green-300" />
              <p className="text-green-600 dark:text-green-300">Profil erfolgreich gespeichert!</p>
            </div>
          )}
        </div>

        {/* Basisdaten */}
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
            Basisdaten
          </h2>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Name *
              </label>
              <input
                type="text"
                value={formData.name}
                onChange={(e) => setFormData(prev => ({ ...prev, name: 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"
                required
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Rolle/Position
              </label>
              <input
                type="text"
                value={formData.role}
                onChange={(e) => setFormData(prev => ({ ...prev, role: 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>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Abteilung
              </label>
              <input
                type="text"
                value={formData.department}
                onChange={(e) => setFormData(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"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Standort
              </label>
              <input
                type="text"
                value={formData.location}
                onChange={(e) => setFormData(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"
              />
            </div>
          </div>
        </div>

        {/* Kontaktdaten */}
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
            Kontaktdaten
          </h2>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                E-Mail
              </label>
              <input
                type="email"
                value={formData.contacts.email}
                onChange={(e) => setFormData(prev => ({ 
                  ...prev, 
                  contacts: { ...prev.contacts, email: 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>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Telefon
              </label>
              <input
                type="tel"
                value={formData.contacts.phone}
                onChange={(e) => setFormData(prev => ({ 
                  ...prev, 
                  contacts: { ...prev.contacts, phone: 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>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Teams-Link
              </label>
              <input
                type="text"
                value={formData.contacts.teams}
                onChange={(e) => setFormData(prev => ({ 
                  ...prev, 
                  contacts: { ...prev.contacts, teams: 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>

        {/* Berufsbilder */}
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
            Berufsbild
          </h2>

          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Kategorie
              </label>
              <select
                value={formData.jobCategory || ''}
                onChange={(e) => setFormData(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="">W\u00e4hlen...</option>
                {JOB_CATEGORIES.map(cat => (
                  <option key={cat} value={cat}>{cat}</option>
                ))}
              </select>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Berufsbezeichnung
              </label>
              <input
                type="text"
                value={formData.jobTitle}
                onChange={(e) => setFormData(prev => ({ ...prev, jobTitle: 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>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Beschreibung
              </label>
              <textarea
                value={formData.jobDesc}
                onChange={(e) => setFormData(prev => ({ ...prev, jobDesc: e.target.value }))}
                rows={3}
                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>

        {/* Kompetenzen */}
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
            Kompetenzen
          </h2>

          <div className="space-y-4">
            {/* Tools */}
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Tools & Software
              </label>
              <div className="flex gap-2 mb-2">
                <input
                  type="text"
                  placeholder="Tool hinzuf\u00fcgen..."
                  onKeyPress={(e) => {
                    if (e.key === 'Enter') {
                      e.preventDefault()
                      const input = e.target as HTMLInputElement
                      if (input.value) {
                        addToArray('tools', input.value)
                        input.value = ''
                      }
                    }
                  }}
                  onFocus={() => {
                    setActiveInput('tools')
                    loadSuggestions('tools', '')
                  }}
                  className="flex-1 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 className="flex flex-wrap gap-2">
                {formData.tools.map((tool, i) => (
                  <span key={i} className="px-3 py-1 bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 rounded-full flex items-center gap-2">
                    {tool}
                    <button
                      type="button"
                      onClick={() => removeFromArray('tools', i)}
                      className="hover:text-red-600"
                    >
                      <X className="w-4 h-4" />
                    </button>
                  </span>
                ))}
              </div>
            </div>

            {/* Methoden */}
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Methoden
              </label>
              <div className="flex gap-2 mb-2">
                <input
                  type="text"
                  placeholder="Methode hinzuf\u00fcgen..."
                  onKeyPress={(e) => {
                    if (e.key === 'Enter') {
                      e.preventDefault()
                      const input = e.target as HTMLInputElement
                      if (input.value) {
                        addToArray('methods', input.value)
                        input.value = ''
                      }
                    }
                  }}
                  className="flex-1 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 className="flex flex-wrap gap-2">
                {formData.methods.map((method, i) => (
                  <span key={i} className="px-3 py-1 bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200 rounded-full flex items-center gap-2">
                    {method}
                    <button
                      type="button"
                      onClick={() => removeFromArray('methods', i)}
                      className="hover:text-red-600"
                    >
                      <X className="w-4 h-4" />
                    </button>
                  </span>
                ))}
              </div>
            </div>
          </div>
        </div>

        {/* Sprachen */}
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
            Sprachkenntnisse
          </h2>

          <div className="space-y-2">
            {formData.languages.map((lang, i) => (
              <div key={i} className="flex gap-2">
                <input
                  type="text"
                  value={lang.code}
                  onChange={(e) => updateLanguage(i, 'code', e.target.value)}
                  placeholder="Sprache (z.B. de, en)"
                  className="flex-1 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"
                />
                <select
                  value={lang.level}
                  onChange={(e) => updateLanguage(i, 'level', e.target.value as any)}
                  className="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"
                >
                  {LANGUAGE_LEVELS.map(level => (
                    <option key={level.value} value={level.value}>{level.label}</option>
                  ))}
                </select>
                <button
                  type="button"
                  onClick={() => removeLanguage(i)}
                  className="p-2 text-red-600 hover:bg-red-100 dark:hover:bg-red-900 rounded-lg"
                >
                  <Trash2 className="w-5 h-5" />
                </button>
              </div>
            ))}
            <button
              type="button"
              onClick={addLanguage}
              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"
            >
              <Plus className="w-5 h-5" />
              Sprache hinzuf\u00fcgen
            </button>
          </div>
        </div>

        {/* Projekte */}
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
            Projekterfahrung
          </h2>

          <div className="space-y-4">
            {formData.projects.map((project, i) => (
              <div key={i} className="p-4 border border-gray-200 dark:border-gray-700 rounded-lg">
                <div className="space-y-3">
                  <input
                    type="text"
                    value={project.title}
                    onChange={(e) => updateProject(i, 'title', e.target.value)}
                    placeholder="Projekttitel"
                    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"
                  />
                  <input
                    type="text"
                    value={project.role || ''}
                    onChange={(e) => updateProject(i, 'role', e.target.value)}
                    placeholder="Ihre Rolle im Projekt"
                    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"
                  />
                  <textarea
                    value={project.summary || ''}
                    onChange={(e) => updateProject(i, 'summary', e.target.value)}
                    placeholder="Kurzbeschreibung"
                    rows={2}
                    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"
                  />
                  <button
                    type="button"
                    onClick={() => removeProject(i)}
                    className="text-red-600 hover:text-red-700"
                  >
                    Projekt entfernen
                  </button>
                </div>
              </div>
            ))}
            <button
              type="button"
              onClick={addProject}
              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"
            >
              <Plus className="w-5 h-5" />
              Projekt hinzuf\u00fcgen
            </button>
          </div>
        </div>

        {/* Datenschutz */}
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
            Datenschutz & Sichtbarkeit
          </h2>

          <div className="space-y-4">
            <div className="flex items-center gap-3">
              <input
                type="checkbox"
                id="consentPublic"
                checked={formData.consentPublicProfile}
                onChange={(e) => setFormData(prev => ({ ...prev, consentPublicProfile: e.target.checked }))}
                className="w-5 h-5 text-blue-600"
              />
              <label htmlFor="consentPublic" className="text-gray-700 dark:text-gray-300">
                Mein Profil darf \u00f6ffentlich angezeigt werden
              </label>
            </div>

            <div className="flex items-center gap-3">
              <input
                type="checkbox"
                id="consentSearch"
                checked={formData.consentSearchable}
                onChange={(e) => setFormData(prev => ({ ...prev, consentSearchable: e.target.checked }))}
                className="w-5 h-5 text-blue-600"
              />
              <label htmlFor="consentSearch" className="text-gray-700 dark:text-gray-300">
                Mein Profil darf in der Suche gefunden werden
              </label>
            </div>

            <div className="p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
              <p className="text-sm text-blue-800 dark:text-blue-200">
                <strong>Hinweis:</strong> Ihre Daten werden ausschlie\u00dflich intern verwendet und nicht an Dritte weitergegeben.
                Sie k\u00f6nnen diese Einstellungen jederzeit \u00e4ndern.
              </p>
            </div>
          </div>
        </div>

        {/* Actions */}
        <div className="flex justify-end gap-4">
          <button
            type="button"
            onClick={() => navigate(-1)}
            className="px-6 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"
          >
            Abbrechen
          </button>
          <button
            type="submit"
            disabled={saving}
            className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 flex items-center gap-2"
          >
            {saving ? (
              <>
                <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
                Speichern...
              </>
            ) : (
              <>
                <Save className="w-5 h-5" />
                Speichern
              </>
            )}
          </button>
        </div>
      </form>
    </div>
  )
}