import { useEffect, useState } from 'react'
import { useAuthStore } from '../stores/authStore'
import { employeeApi } from '../services/api'
import PhotoUpload from '../components/PhotoUpload'
import SkillLevelBar from '../components/SkillLevelBar'
import DeputyManagement from '../components/DeputyManagement'
import OrganizationSelector from '../components/OrganizationSelector'
import { isBooleanSkill } from '../utils/skillRules'

interface SkillSelection { categoryId: string; subCategoryId: string; skillId: string; name: string; level: string }

export default function MyProfile() {
  const { user } = useAuthStore()
  const employeeId = user?.employeeId
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState('')

const [form, setForm] = useState<any | null>(null)
const [catalog, setCatalog] = useState<{ id: string; name: string; subcategories: { id: string; name: string; skills: { id: string; name: string }[] }[] }[]>([])
const [skills, setSkills] = useState<SkillSelection[]>([])
const [activeTab, setActiveTab] = useState<'profile' | 'deputies'>('profile')
const [currentUnitId, setCurrentUnitId] = useState<string | null>(null)
const [myUnits, setMyUnits] = useState<any[]>([])
const AVAILABILITY_OPTIONS = [
  { value: 'available', label: 'Verfügbar' },
  { value: 'busy', label: 'Beschäftigt' },
  { value: 'away', label: 'Abwesend' },
  { value: 'vacation', label: 'Urlaub' },
  { value: 'sick', label: 'Erkrankt' },
  { value: 'training', label: 'Fortbildung' },
  { value: 'operation', label: 'Im Einsatz' },
  { value: 'parttime', label: 'Teilzeit' },
  { value: 'unavailable', label: 'Nicht verfügbar' }
]

  useEffect(() => {
    if (!employeeId) {
      setLoading(false)
      return
    }
    load()
  }, [employeeId])

  const load = async () => {
    if (!employeeId) return
    setLoading(true)
    setError('')
    try {
      // Load employee first
      const data = await employeeApi.getById(employeeId)
      setForm({ ...data, email: user?.email || data.email || '' })
      const mapped: SkillSelection[] = (data.skills || []).map((s: any) => {
        const catStr = s.category || ''
        const [catId, subId] = String(catStr).split('.')
        const categoryId = catId || ''
        const subCategoryId = subId || ''
        const booleanSkill = isBooleanSkill(categoryId, subCategoryId)
        const rawLevel = (s.level ?? '').toString()
        return {
          categoryId,
          subCategoryId,
          skillId: s.id,
          name: s.name,
          level: booleanSkill ? (rawLevel && rawLevel !== '0' ? '1' : '') : rawLevel
        }
      })
      setSkills(mapped)
      
      // Load my organizational units
      try {
        const unitsRes = await fetch(((import.meta as any).env?.VITE_API_URL || 'http://localhost:3004/api') + '/organization/my-units', {
          headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` }
        }).then(r => r.json())
        if (unitsRes?.success && unitsRes.data?.length > 0) {
          setMyUnits(unitsRes.data)
          const primaryUnit = unitsRes.data.find((u: any) => u.isPrimary)
          if (primaryUnit) {
            setCurrentUnitId(primaryUnit.id)
          }
        }
      } catch {
        // ignore unit errors
      }
      
      // Load hierarchy non-critically
      try {
        const hierRes = await fetch(((import.meta as any).env?.VITE_API_URL || 'http://localhost:3004/api') + '/skills/hierarchy', {
          headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` }
        }).then(r => r.json())
        if (hierRes?.success) setCatalog(hierRes.data || [])
      } catch {
        // ignore hierarchy errors; keep profile usable
      }
    } catch (e: any) {
      setError('Profil konnte nicht geladen werden')
    } finally {
      setLoading(false)
    }
  }

  const handleSkillToggle = (categoryId: string, subCategoryId: string, skillId: string, skillName: string) => {
    setSkills(prev => {
      const list = [...prev]
      const idx = list.findIndex(s => s.categoryId === categoryId && s.subCategoryId === subCategoryId && s.skillId === skillId)
      if (idx >= 0) {
        list.splice(idx, 1)
      } else {
        list.push({ categoryId, subCategoryId, skillId, name: skillName, level: isBooleanSkill(categoryId, subCategoryId) ? '1' : '' })
      }
      return list
    })
  }

  const handleSkillLevelChange = (categoryId: string, subCategoryId: string, skillId: string, level: string) => {
    if (isBooleanSkill(categoryId, subCategoryId)) return
    setSkills(prev => prev.map(s => (s.categoryId === categoryId && s.subCategoryId === subCategoryId && s.skillId === skillId) ? { ...s, level } : s))
  }

  const isSkillSelected = (categoryId: string, subCategoryId: string, skillId: string) =>
    skills.some(s => s.categoryId === categoryId && s.subCategoryId === subCategoryId && s.skillId === skillId)

  const getSkillLevel = (categoryId: string, subCategoryId: string, skillId: string) =>
    (skills.find(s => s.categoryId === categoryId && s.subCategoryId === subCategoryId && s.skillId === skillId)?.level) || ''

  const handleOrganizationChange = async (unitId: string | null, unitName: string) => {
    setCurrentUnitId(unitId)
    if (unitId && employeeId) {
      try {
        // Save organization assignment
        await fetch(((import.meta as any).env?.VITE_API_URL || 'http://localhost:3004/api') + '/organization/assignments', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          },
          body: JSON.stringify({
            employeeId: employeeId,
            unitId: unitId,
            role: 'mitarbeiter',
            isPrimary: true
          })
        })
        // Update department field with unit name for backward compatibility
        setForm((prev: any) => ({ ...prev, department: unitName }))
      } catch (error) {
        console.error('Failed to assign unit:', error)
      }
    }
  }

  const onSave = async () => {
    if (!employeeId || !form) return
    setSaving(true)
    setError('')
    setSuccess('')
    try {
      const payload = {
        firstName: form.firstName,
        lastName: form.lastName,
        position: form.position || 'Teammitglied',
        officialTitle: form.officialTitle || null,
        department: form.department || '',
        employeeNumber: form.employeeNumber || undefined,
        email: user?.email || form.email,
        phone: form.phone || '',
        mobile: form.mobile || null,
        office: form.office || null,
        availability: form.availability || 'available',
        skills: skills.map(s => ({
          id: s.skillId,
          name: s.name,
          category: s.categoryId,
          level: isBooleanSkill(s.categoryId, s.subCategoryId) ? null : (Number(s.level) || 3)
        })),
        languages: form.languages || [],
        specializations: form.specializations || []
      }
      await fetch(((import.meta as any).env?.VITE_API_URL || 'http://localhost:3004/api') + `/employees/${employeeId}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        body: JSON.stringify(payload)
      }).then(async r => {
        const d = await r.json()
        if (!r.ok) throw new Error(d?.error?.message || 'Speichern fehlgeschlagen')
      })
      setSuccess('Profil gespeichert')
      await load()
    } catch (e: any) {
      setError(e.message || 'Speichern fehlgeschlagen')
    } finally {
      setSaving(false)
    }
  }

  if (!employeeId) {
    return (
      <div>
        <h1 className="text-title-lg font-poppins font-bold text-primary mb-4">Mein Profil</h1>
        <p className="text-tertiary">Kein Mitarbeitendenprofil mit Ihrem Nutzer verknüpft.</p>
      </div>
    )
  }

  if (loading) {
    return <div className="text-secondary">Lade Profil...</div>
  }
  if (!form) {
    return (
      <div>
        <h1 className="text-title-lg font-poppins font-bold text-primary mb-4">Mein Profil</h1>
        <div className="bg-error-bg text-error px-4 py-3 rounded-input text-sm mb-6">
          {error || 'Profil konnte nicht geladen werden'}
        </div>
      </div>
    )
  }

  return (
    <div>
      <h1 className="text-title-lg font-poppins font-bold text-primary mb-4">Mein Profil</h1>

      {/* Tab Navigation */}
      <div className="flex gap-4 mb-6 border-b border-gray-200 dark:border-gray-700">
        <button
          onClick={() => setActiveTab('profile')}
          className={`pb-2 px-1 ${activeTab === 'profile' ? 'border-b-2 border-blue-600 text-blue-600' : 'text-gray-600 dark:text-gray-400'}`}
        >
          Profildaten
        </button>
        <button
          onClick={() => setActiveTab('deputies')}
          className={`pb-2 px-1 ${activeTab === 'deputies' ? 'border-b-2 border-blue-600 text-blue-600' : 'text-gray-600 dark:text-gray-400'}`}
        >
          Vertretungen
        </button>
      </div>

      {error && (<div className="bg-error-bg text-error px-4 py-3 rounded-input text-sm mb-6">{error}</div>)}
      {success && (<div className="bg-success-bg text-success px-4 py-3 rounded-input text-sm mb-6">{success}</div>)}

      {activeTab === 'deputies' ? (
        <DeputyManagement />
      ) : (
        <>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="card">
          <h2 className="text-title-card font-poppins font-semibold text-primary mb-4">Foto</h2>
          <PhotoUpload employeeId={employeeId} currentPhoto={form.photo} onPhotoUpdate={(url) => setForm((prev: any) => ({ ...prev, photo: url }))} />
        </div>

        <div className="card lg:col-span-2">
          <h2 className="text-title-card font-poppins font-semibold text-primary mb-4">Kontakt & Dienststelle</h2>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-body font-medium text-secondary mb-2">E-Mail</label>
              <input className="input-field w-full disabled:opacity-70" value={user?.email || form.email || ''} disabled readOnly placeholder="wird aus Login übernommen" title="Wird automatisch aus dem Login gesetzt" />
              <p className="text-small text-tertiary mt-1">Wird automatisch aus dem Login übernommen. Änderung ggf. im Admin Panel.</p>
            </div>
            <div>
              <label className="block text-body font-medium text-secondary mb-2">Position</label>
              <input
                className="input-field w-full"
                value={form.position || ''}
                onChange={(e) => setForm((p: any) => ({ ...p, position: e.target.value }))}
                placeholder="z. B. Sachbearbeitung, Teamleitung"
              />
              <p className="text-small text-tertiary mt-1">Beispiele: Sachbearbeitung, Teamleitung, Stabsstelle.</p>
            </div>
            <div>
              <label className="block text-body font-medium text-secondary mb-2">Amtsbezeichnung</label>
              <input
                className="input-field w-full"
                value={form.officialTitle || ''}
                onChange={(e) => setForm((p: any) => ({ ...p, officialTitle: e.target.value }))}
                placeholder="z. B. KOK, KHK, EKHK"
              />
              <p className="text-small text-tertiary mt-1">Freifeld für Amts- bzw. Dienstbezeichnungen (z. B. KOK, RBe, EKHK).</p>
            </div>
            <div>
              <label className="block text-body font-medium text-secondary mb-2">NW-Kennung</label>
              <input className="input-field w-full" value={form.employeeNumber || ''} onChange={(e) => setForm((p: any) => ({ ...p, employeeNumber: e.target.value }))} placeholder="z. B. NW068111" />
              <p className="text-small text-tertiary mt-1">Ihre behördliche Kennung, z. B. NW068111.</p>
            </div>
            <div>
              <label className="block text-body font-medium text-secondary mb-2">Dienststelle</label>
              <OrganizationSelector 
                value={currentUnitId || undefined}
                onChange={handleOrganizationChange}
                disabled={false}
              />
              <p className="text-small text-tertiary mt-1">Wählen Sie Ihre Organisationseinheit aus dem Organigramm.</p>
            </div>
            <div>
              <label className="block text-body font-medium text-secondary mb-2">Telefon</label>
              <input className="input-field w-full" value={form.phone || ''} onChange={(e) => setForm((p: any) => ({ ...p, phone: e.target.value }))} placeholder="z. B. +49 30 12345-100" />
              <p className="text-small text-tertiary mt-1">Bitte Rufnummern im internationalen Format angeben (z. B. +49 ...).</p>
            </div>
            <div>
              <label className="block text-body font-medium text-secondary mb-2">Mobil</label>
              <input className="input-field w-full" value={form.mobile || ''} onChange={(e) => setForm((p: any) => ({ ...p, mobile: e.target.value }))} placeholder="z. B. +49 171 1234567" />
              <p className="text-small text-tertiary mt-1">Bitte Rufnummern im internationalen Format angeben (z. B. +49 ...).</p>
            </div>
            <div>
              <label className="block text-body font-medium text-secondary mb-2">Büro</label>
              <input className="input-field w-full" value={form.office || ''} onChange={(e) => setForm((p: any) => ({ ...p, office: e.target.value }))} placeholder="z. B. Gebäude A, 3.OG, Raum 3.12" />
              <p className="text-small text-tertiary mt-1">Angabe zum Standort, z. B. Gebäude, Etage und Raum.</p>
            </div>
            <div>
              <label className="block text-body font-medium text-secondary mb-2">Verfügbarkeit</label>
              <select
                className="input-field w-full"
                value={form.availability || 'available'}
                onChange={(e) => setForm((p: any) => ({ ...p, availability: e.target.value }))}
              >
                {AVAILABILITY_OPTIONS.map(option => (
                  <option key={option.value} value={option.value}>{option.label}</option>
                ))}
              </select>
              <p className="text-small text-tertiary mt-1">Dieser Status wird in der Mitarbeitendenübersicht und Teamplanung angezeigt.</p>
            </div>
          </div>
        </div>
      </div>

      <div className="card mt-6">
        <h2 className="text-title-card font-poppins font-semibold text-primary mb-4">Kompetenzen</h2>
        <div className="space-y-4">
          {catalog.map(category => (
            <div key={category.id}>
              <h3 className="text-body font-semibold text-secondary mb-2">{category.name}</h3>
              {category.subcategories.map(sub => (
                <div key={`${category.id}-${sub.id}`} className="mb-3">
                  <p className="text-small text-tertiary mb-2">{sub.name}</p>
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2">
                    {sub.skills.map(skill => {
                      const booleanSkill = isBooleanSkill(category.id, sub.id)
                      const selected = isSkillSelected(category.id, sub.id, skill.id)
                      return (
                        <div
                          key={`${category.id}-${sub.id}-${skill.id}`}
                          className={`p-2 border rounded-input ${selected ? 'border-primary-blue bg-bg-accent' : 'border-border-default'}`}
                        >
                          <label className="flex items-center justify-between">
                            <span className="text-body text-secondary">
                              <input
                                type="checkbox"
                                className="mr-2"
                                checked={selected}
                                onChange={() => handleSkillToggle(category.id, sub.id, skill.id, skill.name)}
                              />
                              {skill.name}
                            </span>
                            {selected && (
                              booleanSkill ? (
                                <span className="ml-3 text-small font-medium text-green-700 dark:text-green-400">Ja</span>
                              ) : (
                                <div className="ml-3 flex-1">
                                  <SkillLevelBar
                                    value={Number(getSkillLevel(category.id, sub.id, skill.id)) || ''}
                                    onChange={(val) => handleSkillLevelChange(category.id, sub.id, skill.id, String(val))}
                                  />
                                </div>
                              )
                            )}
                          </label>
                        </div>
                      )
                    })}
                  </div>
                </div>
              ))}
            </div>
          ))}
        </div>
      </div>

      <div className="flex justify-end mt-6">
        <button onClick={onSave} disabled={saving} className="btn-primary">
          {saving ? 'Speichere...' : 'Änderungen speichern'}
        </button>
      </div>
      
      </>
      )}
    </div>
  )
}
