import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { useAuth } from '../contexts/AuthContext'
import { usePermissions } from '../hooks/usePermissions'

const Spaces = () => {
  const navigate = useNavigate()
  const { authFetch } = useAuth()
  const { canCreateSpace, canDeleteSpace, refreshPermissions } = usePermissions()
  const [spaces, setSpaces] = useState([])
  const [showForm, setShowForm] = useState(false)
  const [formData, setFormData] = useState({
    name: '',
    description: ''
  })
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const [fetchError, setFetchError] = useState('')
  const [showDeleteModal, setShowDeleteModal] = useState(false)
  const [spaceToDelete, setSpaceToDelete] = useState(null)
  const [fqdnCount, setFqdnCount] = useState(0)
  const [confirmChecked, setConfirmChecked] = useState(false)
  const [deleteFqdnsChecked, setDeleteFqdnsChecked] = useState(false)
  const [copiedId, setCopiedId] = useState(null)

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

  const fetchSpaces = async () => {
    try {
      setFetchError('')
      const response = await authFetch('/api/spaces')
      if (response.ok) {
        const data = await response.json()
        // Stelle sicher, dass data ein Array ist
        setSpaces(Array.isArray(data) ? data : [])
      } else {
        const errorText = `Fehler beim Abrufen der Spaces: ${response.status}`
        console.error(errorText)
        setFetchError(errorText)
        setSpaces([])
      }
    } catch (err) {
      const errorText = 'Fehler beim Abrufen der Spaces. Bitte stellen Sie sicher, dass das Backend läuft.'
      console.error('Error fetching spaces:', err)
      setFetchError(errorText)
      setSpaces([])
    }
  }

  const handleSubmit = async (e) => {
    e.preventDefault()
    setError('')
    setLoading(true)

    if (!formData.name.trim()) {
      setError('Bitte geben Sie einen Namen ein.')
      setLoading(false)
      return
    }

    try {
      const response = await authFetch('/api/spaces', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData),
      })

      if (response.ok) {
        const newSpace = await response.json()
        setSpaces([...spaces, newSpace])
        setFormData({ name: '', description: '' })
        setShowForm(false)
        // Aktualisiere Berechtigungen nach dem Erstellen eines Spaces
        refreshPermissions()
      } else {
        const errorData = await response.json()
        setError(errorData.error || 'Fehler beim Erstellen des Space')
      }
    } catch (err) {
      setError('Fehler beim Erstellen des Space')
      console.error('Error creating space:', err)
    } finally {
      setLoading(false)
    }
  }

  const handleChange = (e) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value
    })
  }

  const handleDelete = async (space) => {
    // Hole die Anzahl der FQDNs für diesen Space
    let count = 0
    try {
      const countResponse = await authFetch(`/api/spaces/${space.id}/fqdns/count`)
      if (countResponse.ok) {
        const countData = await countResponse.json()
        count = countData.count || 0
      }
    } catch (err) {
      console.error('Error fetching FQDN count:', err)
      count = 0
    }

    // Setze State und öffne Modal erst nach dem Laden der FQDN-Anzahl
    setFqdnCount(count)
    setSpaceToDelete(space)
    setConfirmChecked(false)
    setDeleteFqdnsChecked(false)
    setShowDeleteModal(true)
  }

  const confirmDelete = async () => {
    if (!confirmChecked || !spaceToDelete) {
      return
    }

    // Wenn FQDNs vorhanden sind, muss die Checkbox aktiviert sein
    if (fqdnCount > 0 && !deleteFqdnsChecked) {
      alert('Bitte aktivieren Sie die Checkbox, um die FQDNs mitzulöschen.')
      return
    }

    try {
      const url = fqdnCount > 0 && deleteFqdnsChecked
        ? `/api/spaces/${spaceToDelete.id}?deleteFqdns=true`
        : `/api/spaces/${spaceToDelete.id}`

      const response = await authFetch(url, {
        method: 'DELETE',
      })

      if (response.ok) {
        setSpaces(spaces.filter(space => space.id !== spaceToDelete.id))
        setShowDeleteModal(false)
        setSpaceToDelete(null)
        setConfirmChecked(false)
        setDeleteFqdnsChecked(false)
        setFqdnCount(0)
        // Aktualisiere Berechtigungen nach dem Löschen eines Spaces
        refreshPermissions()
      } else {
        const errorText = await response.text()
        let errorMessage = 'Fehler beim Löschen des Space'
        try {
          const errorData = JSON.parse(errorText)
          errorMessage = errorData.error || errorText
        } catch {
          errorMessage = errorText || errorMessage
        }
        alert(errorMessage)
      }
    } catch (err) {
      console.error('Error deleting space:', err)
      alert('Fehler beim Löschen des Space')
    }
  }

  const cancelDelete = () => {
    setShowDeleteModal(false)
    setSpaceToDelete(null)
    setConfirmChecked(false)
    setDeleteFqdnsChecked(false)
    setFqdnCount(0)
  }

  const copyToClipboard = async (id, e) => {
    e.stopPropagation()
    try {
      await navigator.clipboard.writeText(id)
      setCopiedId(id)
      setTimeout(() => setCopiedId(null), 2000)
    } catch (err) {
      console.error('Fehler beim Kopieren:', err)
    }
  }

  return (
    <div className="p-8 min-h-full bg-gradient-to-r from-slate-700 to-slate-900">
      <div className="max-w-4xl mx-auto">
        <div className="flex items-center justify-between mb-8">
          <div>
            <h1 className="text-4xl font-bold text-white mb-2">Spaces</h1>
            <p className="text-lg text-slate-200">
              Verwalten Sie Ihre Spaces und Arbeitsbereiche.
            </p>
          </div>
          <button
            onClick={() => setShowForm(!showForm)}
            disabled={!canCreateSpace() && !showForm}
            className={`px-6 py-3 font-semibold rounded-lg shadow-lg transition-all duration-200 ${
              canCreateSpace() || showForm
                ? 'bg-blue-600 hover:bg-blue-700 text-white hover:shadow-xl'
                : 'bg-slate-600 text-slate-400 cursor-not-allowed opacity-50'
            }`}
            title={!canCreateSpace() && !showForm ? 'Keine Berechtigung zum Erstellen von Spaces' : ''}
          >
            {showForm ? 'Abbrechen' : '+ Neuer Space'}
          </button>
        </div>

        {/* Create Space Form */}
        {showForm && (
          <div className="bg-slate-800/80 backdrop-blur-sm rounded-lg shadow-xl border border-slate-600/50 p-6 mb-6">
            <h2 className="text-2xl font-semibold text-white mb-4">
              Neuen Space erstellen
            </h2>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div>
                <label htmlFor="name" className="block text-sm font-medium text-slate-200 mb-2">
                  Name *
                </label>
                <input
                  type="text"
                  id="name"
                  name="name"
                  value={formData.name}
                  onChange={handleChange}
                  className="w-full px-4 py-2 bg-slate-700/50 border border-slate-600 rounded-lg text-white placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  placeholder="Geben Sie einen Namen ein"
                  required
                />
              </div>
              <div>
                <label htmlFor="description" className="block text-sm font-medium text-slate-200 mb-2">
                  Beschreibung
                </label>
                <textarea
                  id="description"
                  name="description"
                  value={formData.description}
                  onChange={handleChange}
                  rows="4"
                  className="w-full px-4 py-2 bg-slate-700/50 border border-slate-600 rounded-lg text-white placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"
                  placeholder="Geben Sie eine Beschreibung ein (optional)"
                />
              </div>
              {error && (
                <div className="p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-red-300 text-sm">
                  {error}
                </div>
              )}
              <div className="flex gap-3">
                <button
                  type="submit"
                  disabled={loading}
                  className="px-6 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-blue-800 disabled:cursor-not-allowed text-white font-semibold rounded-lg transition-all duration-200"
                >
                  {loading ? 'Wird erstellt...' : 'Space erstellen'}
                </button>
                <button
                  type="button"
                  onClick={() => {
                    setShowForm(false)
                    setFormData({ name: '', description: '' })
                    setError('')
                  }}
                  className="px-6 py-2 bg-slate-600 hover:bg-slate-700 text-white font-semibold rounded-lg transition-colors duration-200"
                >
                  Abbrechen
                </button>
              </div>
            </form>
          </div>
        )}

        {/* Spaces List */}
        <div className="bg-slate-800/80 backdrop-blur-sm rounded-lg shadow-xl border border-slate-600/50 p-6">
          <h2 className="text-2xl font-semibold text-white mb-4">
            Ihre Spaces
          </h2>
          {fetchError && (
            <div className="mb-4 p-4 bg-red-500/20 border border-red-500/50 rounded-lg">
              <p className="text-red-300 mb-2">{fetchError}</p>
              <button
                onClick={() => fetchSpaces()}
                className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg transition-all duration-200"
              >
                Erneut versuchen
              </button>
            </div>
          )}
          {!fetchError && spaces.length === 0 ? (
            <p className="text-slate-300 text-center py-8">
              Noch keine Spaces vorhanden. Erstellen Sie Ihren ersten Space!
            </p>
          ) : (
            <div className="space-y-4">
              {spaces.map((space) => (
                <div
                  key={space.id || Math.random()}
                  className="bg-slate-700/50 rounded-lg p-4 border border-slate-600/50 hover:border-slate-500 transition-colors cursor-pointer shadow-soft"
                  onClick={() => navigate(`/spaces/${space.id}`)}
                >
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      <h3 className="text-xl font-semibold text-white mb-2">
                        {space.name || 'Unbenannt'}
                      </h3>
                      {space.description && (
                        <p className="text-slate-300 mb-2">{space.description}</p>
                      )}
                      <p className="text-xs text-slate-400">
                        Erstellt: {space.createdAt ? new Date(space.createdAt).toLocaleString('de-DE') : 'Unbekannt'}
                      </p>
                      {space.id && (
                        <p className="text-xs text-slate-500 font-mono mt-1">
                          ID: {space.id}
                        </p>
                      )}
                    </div>
                    <div className="flex gap-2 ml-4">
                      <button
                        onClick={(e) => copyToClipboard(space.id, e)}
                        className="p-2 text-blue-400 hover:text-blue-300 hover:bg-blue-500/20 rounded-lg transition-colors"
                        title={copiedId === space.id ? 'Kopiert!' : 'ID kopieren'}
                        aria-label="ID kopieren"
                      >
                        {copiedId === space.id ? (
                          <svg
                            className="w-5 h-5"
                            fill="none"
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            strokeWidth="2"
                            viewBox="0 0 24 24"
                            stroke="currentColor"
                          >
                            <path d="M5 13l4 4L19 7" />
                          </svg>
                        ) : (
                          <svg
                            className="w-5 h-5"
                            fill="none"
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            strokeWidth="2"
                            viewBox="0 0 24 24"
                            stroke="currentColor"
                          >
                            <path d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
                          </svg>
                        )}
                      </button>
                      <button
                        onClick={(e) => {
                          e.stopPropagation()
                          if (canDeleteSpace(space.id)) {
                            handleDelete(space)
                          }
                        }}
                        disabled={!canDeleteSpace(space.id)}
                        className={`p-2 rounded-lg transition-colors ${
                          canDeleteSpace(space.id)
                            ? 'text-red-400 hover:text-red-300 hover:bg-red-500/20'
                            : 'text-slate-500 cursor-not-allowed opacity-50'
                        }`}
                        title={canDeleteSpace(space.id) ? 'Space löschen' : 'Keine Berechtigung zum Löschen von Spaces'}
                        aria-label={canDeleteSpace(space.id) ? 'Space löschen' : 'Keine Berechtigung'}
                      >
                        <svg
                          className="w-5 h-5"
                          fill="none"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          strokeWidth="2"
                          viewBox="0 0 24 24"
                          stroke="currentColor"
                        >
                          <path d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                        </svg>
                      </button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Delete Confirmation Modal */}
      {showDeleteModal && spaceToDelete && (
        <div className="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 flex items-center justify-center p-4">
          <div className="bg-slate-800 rounded-xl shadow-2xl border border-slate-600/50 max-w-md w-full p-6">
            <div className="flex items-center mb-4">
              <div className="flex-shrink-0 w-12 h-12 bg-red-500/20 rounded-full flex items-center justify-center mr-4">
                <svg
                  className="w-6 h-6 text-red-400"
                  fill="none"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth="2"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                >
                  <path d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                </svg>
              </div>
              <h3 className="text-xl font-bold text-white">
                Space löschen
              </h3>
            </div>

            <div className="mb-6">
              <p className="text-slate-300 mb-4">
                Möchten Sie den Space <span className="font-semibold text-white">{spaceToDelete.name}</span> wirklich löschen?
              </p>

              {fqdnCount > 0 ? (
                <div className="mb-4 p-4 bg-yellow-500/20 border border-yellow-500/50 rounded-lg">
                  <p className="text-yellow-300 text-sm mb-3">
                    ⚠️ Dieser Space enthält <span className="font-semibold">{fqdnCount}</span> {fqdnCount === 1 ? 'FQDN' : 'FQDNs'}. 
                    Der Space kann nur gelöscht werden, wenn Sie die FQDNs mitlöschen.
                  </p>
                  <label className="flex items-start cursor-pointer group">
                    <input
                      type="checkbox"
                      checked={deleteFqdnsChecked}
                      onChange={(e) => setDeleteFqdnsChecked(e.target.checked)}
                      className="mt-1 w-5 h-5 text-red-600 bg-slate-700 border-slate-600 rounded focus:ring-2 focus:ring-red-500 focus:ring-offset-2 focus:ring-offset-slate-800 cursor-pointer"
                    />
                    <span className="ml-3 text-sm text-slate-300 group-hover:text-white transition-colors">
                      Alle {fqdnCount} {fqdnCount === 1 ? 'FQDN' : 'FQDNs'} mit diesem Space löschen
                    </span>
                  </label>
                </div>
              ) : (
                <p className="text-sm text-green-400 mb-4">
                  ✓ Dieser Space enthält keine FQDNs und kann gelöscht werden.
                </p>
              )}

              <p className="text-sm text-red-400 mb-4">
                Diese Aktion kann nicht rückgängig gemacht werden.
              </p>

              <label className="flex items-start cursor-pointer group">
                <input
                  type="checkbox"
                  checked={confirmChecked}
                  onChange={(e) => setConfirmChecked(e.target.checked)}
                  className="mt-1 w-5 h-5 text-red-600 bg-slate-700 border-slate-600 rounded focus:ring-2 focus:ring-red-500 focus:ring-offset-2 focus:ring-offset-slate-800 cursor-pointer"
                />
                <span className="ml-3 text-sm text-slate-300 group-hover:text-white transition-colors">
                  Ich bestätige, dass ich diesen Space unwiderruflich löschen möchte
                </span>
              </label>
            </div>

            <div className="flex gap-3">
              <button
                onClick={confirmDelete}
                disabled={!confirmChecked || (fqdnCount > 0 && !deleteFqdnsChecked)}
                className="flex-1 px-4 py-2 bg-red-600 hover:bg-red-700 disabled:bg-slate-700 disabled:text-slate-500 disabled:cursor-not-allowed text-white font-semibold rounded-lg transition-all duration-200"
              >
                Löschen
              </button>
              <button
                onClick={cancelDelete}
                className="flex-1 px-4 py-2 bg-slate-600 hover:bg-slate-700 text-white font-semibold rounded-lg transition-colors duration-200"
              >
                Abbrechen
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

export default Spaces

