'use client'

import { useState } from 'react'
import { Escalation, priorityColors, priorityLabels, statusColors, statusLabels, categoryLabels, formatDate } from './types'

interface DrawerProps {
  escalation: Escalation
  onClose: () => void
  onUpdated: () => void
}

export function EscalationDetailDrawer({ escalation, onClose, onUpdated }: DrawerProps) {
  const [editAssignee, setEditAssignee] = useState(escalation.assignee || '')
  const [editPriority, setEditPriority] = useState(escalation.priority)
  const [editDueDate, setEditDueDate] = useState(
    escalation.due_date ? escalation.due_date.slice(0, 10) : ''
  )
  const [saving, setSaving] = useState(false)
  const [statusSaving, setStatusSaving] = useState(false)
  const [isDeleting, setIsDeleting] = useState(false)

  async function handleDeleteEscalation() {
    if (!window.confirm(`Eskalation "${escalation.title}" wirklich löschen?`)) return
    setIsDeleting(true)
    try {
      const res = await fetch(`/api/sdk/v1/escalations/${escalation.id}`, { method: 'DELETE' })
      if (!res.ok) throw new Error(`Fehler: ${res.status}`)
      onUpdated()
      onClose()
    } catch (err) {
      console.error('Löschen fehlgeschlagen:', err)
      alert('Löschen fehlgeschlagen.')
    } finally {
      setIsDeleting(false)
    }
  }

  async function handleSaveEdit() {
    setSaving(true)
    try {
      await fetch(`/api/sdk/v1/escalations/${escalation.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          assignee: editAssignee || null,
          priority: editPriority,
          due_date: editDueDate || null,
        }),
      })
      onUpdated()
    } finally {
      setSaving(false)
    }
  }

  async function handleStatusChange(newStatus: string) {
    setStatusSaving(true)
    try {
      await fetch(`/api/sdk/v1/escalations/${escalation.id}/status`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status: newStatus }),
      })
      onUpdated()
      onClose()
    } finally {
      setStatusSaving(false)
    }
  }

  return (
    <div className="fixed inset-0 z-40 flex justify-end">
      <div className="absolute inset-0 bg-black/30" onClick={onClose} />
      <div className="relative w-full max-w-md bg-white shadow-2xl flex flex-col h-full overflow-y-auto">
        <div className="p-6 border-b border-gray-100 flex items-start justify-between">
          <div className="flex-1 pr-4">
            <div className="flex items-center gap-2 mb-2">
              <span className={`px-2 py-0.5 text-xs rounded-full ${priorityColors[escalation.priority]}`}>
                {priorityLabels[escalation.priority]}
              </span>
              <span className={`px-2 py-0.5 text-xs rounded-full ${statusColors[escalation.status]}`}>
                {statusLabels[escalation.status]}
              </span>
              {escalation.category && (
                <span className="px-2 py-0.5 text-xs rounded-full bg-purple-100 text-purple-700">
                  {categoryLabels[escalation.category] || escalation.category}
                </span>
              )}
            </div>
            <h2 className="text-lg font-bold text-gray-900">{escalation.title}</h2>
          </div>
          <button
            onClick={onClose}
            className="p-2 hover:bg-gray-100 rounded-lg transition-colors text-gray-500"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>

        <div className="p-6 space-y-6 flex-1">
          {escalation.description && (
            <div>
              <h3 className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-1">Beschreibung</h3>
              <p className="text-sm text-gray-700">{escalation.description}</p>
            </div>
          )}

          <div className="grid grid-cols-2 gap-4 text-sm">
            <div>
              <span className="text-gray-500 text-xs">Erstellt</span>
              <p className="font-medium text-gray-800">{formatDate(escalation.created_at)}</p>
            </div>
            {escalation.reporter && (
              <div>
                <span className="text-gray-500 text-xs">Gemeldet von</span>
                <p className="font-medium text-gray-800">{escalation.reporter}</p>
              </div>
            )}
            {escalation.source_module && (
              <div>
                <span className="text-gray-500 text-xs">Quell-Modul</span>
                <p className="font-medium text-gray-800">{escalation.source_module}</p>
              </div>
            )}
            {escalation.resolved_at && (
              <div>
                <span className="text-gray-500 text-xs">Geloest am</span>
                <p className="font-medium text-green-700">{formatDate(escalation.resolved_at)}</p>
              </div>
            )}
          </div>

          <div className="border border-gray-200 rounded-xl p-4 space-y-4">
            <h3 className="text-sm font-semibold text-gray-700">Bearbeiten</h3>
            <div>
              <label className="block text-xs font-medium text-gray-500 mb-1">Zugewiesen an</label>
              <input
                type="text"
                value={editAssignee}
                onChange={e => setEditAssignee(e.target.value)}
                className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-purple-500"
                placeholder="Name oder Team"
              />
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block text-xs font-medium text-gray-500 mb-1">Prioritaet</label>
                <select
                  value={editPriority}
                  onChange={e => setEditPriority(e.target.value as Escalation['priority'])}
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-purple-500"
                >
                  <option value="low">Niedrig</option>
                  <option value="medium">Mittel</option>
                  <option value="high">Hoch</option>
                  <option value="critical">Kritisch</option>
                </select>
              </div>
              <div>
                <label className="block text-xs font-medium text-gray-500 mb-1">Faelligkeit</label>
                <input
                  type="date"
                  value={editDueDate}
                  onChange={e => setEditDueDate(e.target.value)}
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-purple-500"
                />
              </div>
            </div>
            <button
              onClick={handleSaveEdit}
              disabled={saving}
              className="w-full py-2 text-sm bg-gray-800 text-white rounded-lg hover:bg-gray-900 transition-colors disabled:opacity-50"
            >
              {saving ? 'Speichern…' : 'Aenderungen speichern'}
            </button>
          </div>

          <div>
            <h3 className="text-sm font-semibold text-gray-700 mb-3">Status-Aktionen</h3>
            <div className="flex flex-col gap-2">
              {escalation.status === 'open' && (
                <button
                  onClick={() => handleStatusChange('in_progress')}
                  disabled={statusSaving}
                  className="w-full py-2 text-sm bg-yellow-500 text-white rounded-lg hover:bg-yellow-600 transition-colors disabled:opacity-50"
                >
                  In Bearbeitung nehmen
                </button>
              )}
              {escalation.status === 'in_progress' && (
                <button
                  onClick={() => handleStatusChange('escalated')}
                  disabled={statusSaving}
                  className="w-full py-2 text-sm bg-orange-500 text-white rounded-lg hover:bg-orange-600 transition-colors disabled:opacity-50"
                >
                  Eskalieren
                </button>
              )}
              {(escalation.status === 'escalated' || escalation.status === 'in_progress') && (
                <button
                  onClick={() => handleStatusChange('resolved')}
                  disabled={statusSaving}
                  className="w-full py-2 text-sm bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors disabled:opacity-50"
                >
                  Loesen
                </button>
              )}
              {escalation.status === 'resolved' && (
                <button
                  onClick={() => handleStatusChange('closed')}
                  disabled={statusSaving}
                  className="w-full py-2 text-sm bg-gray-500 text-white rounded-lg hover:bg-gray-600 transition-colors disabled:opacity-50"
                >
                  Schliessen
                </button>
              )}
              {escalation.status === 'closed' && (
                <p className="text-sm text-gray-400 text-center py-2">Eskalation ist geschlossen.</p>
              )}
            </div>
          </div>

          <div className="pt-2 border-t border-gray-100">
            <button
              onClick={handleDeleteEscalation}
              disabled={isDeleting}
              className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 text-sm transition-colors disabled:opacity-50"
            >
              {isDeleting ? 'Löschen...' : 'Löschen'}
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}
