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

export default function DeputyManagement() {
  const [asPrincipal, setAsPrincipal] = useState<any[]>([])
  const [asDeputy, setAsDeputy] = useState<any[]>([])
  const [availableEmployees, setAvailableEmployees] = useState<Employee[]>([])
  const [showAddDialog, setShowAddDialog] = useState(false)
  const [loading, setLoading] = useState(true)
  const [formData, setFormData] = useState({
    deputyId: '',
    validFrom: new Date().toISOString().split('T')[0],
    validUntil: '',
    reason: '',
    canDelegate: true,
    unitId: ''
  })
  const { user } = useAuthStore()

  useEffect(() => {
    loadDeputies()
    loadEmployees()
  }, [])

  const loadDeputies = async () => {
    try {
      const response = await api.get('/organization/deputies/my')
      if (response.data.success) {
        // Backend returns { asDeputy, asPrincipal }
        setAsPrincipal(response.data.data.asPrincipal || [])
        setAsDeputy(response.data.data.asDeputy || [])
      }
    } catch (error) {
      console.error('Failed to load deputies:', error)
    } finally {
      setLoading(false)
    }
  }

  const loadEmployees = async () => {
    try {
      const response = await api.get('/employees/public')
      if (response.data.success) {
        setAvailableEmployees(response.data.data)
      }
    } catch (error) {
      console.error('Failed to load employees:', error)
    }
  }

  const handleAddDeputy = async () => {
    try {
      const response = await api.post('/organization/deputies/my', {
        ...formData,
        validFrom: new Date(formData.validFrom).toISOString(),
        validUntil: formData.validUntil ? new Date(formData.validUntil).toISOString() : null
      })
      
      if (response.data.success) {
        await loadDeputies()
        setShowAddDialog(false)
        resetForm()
      }
    } catch (error) {
      console.error('Failed to add deputy:', error)
    }
  }

  const handleRemoveDeputy = async (id: string) => {
    if (!confirm('Möchten Sie diese Vertretung wirklich entfernen?')) return
    
    try {
      await api.delete(`/organization/deputies/${id}`)
      await loadDeputies()
    } catch (error) {
      console.error('Failed to remove deputy:', error)
    }
  }

  const handleDelegate = async (assignmentId: string) => {
    const toDeputyId = prompt('Bitte geben Sie die Personen-ID des neuen Vertretenden ein:')
    if (!toDeputyId) return

    const reason = prompt('Grund für die Weitergabe (optional):')
    
    try {
      const response = await api.post('/organization/deputies/delegate', {
        assignmentId,
        toDeputyId,
        validFrom: new Date().toISOString(),
        reason
      })
      
      if (response.data.success) {
        await loadDeputies()
        alert('Vertretung erfolgreich weitergegeben')
      }
    } catch (error) {
      console.error('Failed to delegate:', error)
      alert('Fehler beim Weitergeben der Vertretung')
    }
  }

  const resetForm = () => {
    setFormData({
      deputyId: '',
      validFrom: new Date().toISOString().split('T')[0],
      validUntil: '',
      reason: '',
      canDelegate: true,
      unitId: ''
    })
  }

  if (loading) {
    return <div className="p-4">Lade Vertretungen...</div>
  }

  return (
    <div className="p-6">
      <div className="mb-6">
        <h2 className="text-2xl font-bold mb-2 dark:text-white">Meine Vertretungen</h2>
        <p className="text-gray-600 dark:text-gray-400">
          Verwalten Sie hier Ihre Vertretungsregelungen
        </p>
      </div>

      {/* Current Deputies */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-6">
        <div className="flex justify-between items-center mb-4">
          <h3 className="text-lg font-semibold dark:text-white">Aktuelle Vertretungen</h3>
          <button
            onClick={() => setShowAddDialog(true)}
            className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
          >
            + Vertretung hinzufügen
          </button>
        </div>

        {asPrincipal.length > 0 ? (
          <div className="space-y-3">
            {asPrincipal.map((deputy: any) => (
              <div
                key={deputy.id}
                className="border dark:border-gray-700 rounded-lg p-4 flex items-center justify-between"
              >
                <div className="flex items-center gap-4">
                  <div className="w-12 h-12 rounded-full bg-gray-200 dark:bg-gray-600 flex items-center justify-center">
                    👤
                  </div>
                  <div>
                    <p className="font-medium dark:text-white">{deputy.deputyName}</p>
                    <p className="text-sm text-gray-600 dark:text-gray-400">
                      {new Date(deputy.validFrom).toLocaleDateString('de-DE')}
                      {deputy.validUntil && ` - ${new Date(deputy.validUntil).toLocaleDateString('de-DE')}`}
                    </p>
                    {deputy.reason && (
                      <p className="text-sm text-gray-500 dark:text-gray-500">
                        Grund: {deputy.reason}
                      </p>
                    )}
                    {deputy.unitName && (
                      <p className="text-sm text-gray-500 dark:text-gray-500">
                        Für: {deputy.unitName}
                      </p>
                    )}
                  </div>
                </div>
                <div className="flex gap-2">
                  {(deputy.canDelegate === 1 || deputy.canDelegate === true) && (
                    <button
                      onClick={() => handleDelegate(deputy.id)}
                      className="px-3 py-1 text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded"
                      title="Vertretung weitergeben"
                    >
                      ↔️ Weitergeben
                    </button>
                  )}
                  <button
                    onClick={() => handleRemoveDeputy(deputy.id)}
                    className="px-3 py-1 text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded"
                  >
                    Entfernen
                  </button>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <p className="text-gray-500 dark:text-gray-400">
            Keine aktiven Vertretungen vorhanden
          </p>
        )}
      </div>

      {/* Add Deputy Dialog */}
      {showAddDialog && (
        <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-6 max-w-md w-full">
            <h3 className="text-xl font-bold mb-4 dark:text-white">
              Vertretung hinzufügen
            </h3>

            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium mb-1 dark:text-gray-300">
                  Vertreter *
                </label>
                <select
                  value={formData.deputyId}
                  onChange={(e) => setFormData({ ...formData, deputyId: e.target.value })}
                  className="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:border-gray-600"
                  required
                >
                  <option value="">Bitte wählen...</option>
                  {availableEmployees.map(emp => (
                    <option key={emp.id} value={emp.id}>
                      {emp.firstName} {emp.lastName} - {emp.position}
                    </option>
                  ))}
                </select>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium mb-1 dark:text-gray-300">
                    Von *
                  </label>
                  <input
                    type="date"
                    value={formData.validFrom}
                    onChange={(e) => setFormData({ ...formData, validFrom: e.target.value })}
                    className="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:border-gray-600"
                    required
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium mb-1 dark:text-gray-300">
                    Bis (optional)
                  </label>
                  <input
                    type="date"
                    value={formData.validUntil}
                    onChange={(e) => setFormData({ ...formData, validUntil: e.target.value })}
                    className="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:border-gray-600"
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium mb-1 dark:text-gray-300">
                  Grund (optional)
                </label>
                <select
                  value={formData.reason}
                  onChange={(e) => setFormData({ ...formData, reason: e.target.value })}
                  className="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:border-gray-600"
                >
                  <option value="">Kein Grund angegeben</option>
                  <option value="Urlaub">Urlaub</option>
                  <option value="Dienstreise">Dienstreise</option>
                  <option value="Fortbildung">Fortbildung</option>
                  <option value="Krankheit">Krankheit</option>
                  <option value="Sonstiges">Sonstiges</option>
                </select>
              </div>

              <div>
                <label className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    checked={formData.canDelegate}
                    onChange={(e) => setFormData({ ...formData, canDelegate: e.target.checked })}
                    className="rounded"
                  />
                  <span className="text-sm dark:text-gray-300">
                    Vertreter darf Vertretung weitergeben
                  </span>
                </label>
              </div>
            </div>

            <div className="flex justify-end gap-2 mt-6">
              <button
                onClick={() => {
                  setShowAddDialog(false)
                  resetForm()
                }}
                className="px-4 py-2 text-gray-600 dark:text-gray-400 hover:text-gray-800"
              >
                Abbrechen
              </button>
              <button
                onClick={handleAddDeputy}
                className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
              >
                Hinzufügen
              </button>
            </div>
          </div>
        </div>
      )}

      {/* My Deputy Roles */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
        <h3 className="text-lg font-semibold mb-4 dark:text-white">
          Ich vertrete
        </h3>
        {asDeputy.length > 0 ? (
          <div className="space-y-3">
            {asDeputy.map((item: any) => (
              <div key={item.id} className="border dark:border-gray-700 rounded-lg p-4 flex items-center justify-between">
                <div>
                  <p className="font-medium dark:text-white">{item.principalName}</p>
                  <p className="text-sm text-gray-600 dark:text-gray-400">
                    {new Date(item.validFrom).toLocaleDateString('de-DE')}
                    {item.validUntil && ` - ${new Date(item.validUntil).toLocaleDateString('de-DE')}`}
                  </p>
                  {item.unitName && (
                    <p className="text-sm text-gray-500 dark:text-gray-500">Für: {item.unitName}</p>
                  )}
                </div>
              </div>
            ))}
          </div>
        ) : (
          <p className="text-gray-500 dark:text-gray-400 text-sm">
            Keine Einträge.
          </p>
        )}
      </div>
    </div>
  )
}
