'use client'

import React, { useEffect, useState, useCallback } from 'react'
import Link from 'next/link'
import { useParams } from 'next/navigation'

interface AgentDetail {
  id: string
  name: string
  description: string
  color: string
  icon: string
  status: 'active' | 'inactive' | 'error'
  version: string
  soulContent: string
  createdAt: string | null
  updatedAt: string | null
  fileSize: number
  stats: {
    sessionsToday: number
    avgResponseTime: string
    successRate: string
  }
}

interface BackupEntry {
  filename: string
  timestamp: number
  size: number
}

function StatusBadge({ status }: { status: string }) {
  const colors = {
    active: 'bg-green-100 text-green-700',
    inactive: 'bg-gray-100 text-gray-600',
    error: 'bg-red-100 text-red-700',
  }
  const labels = { active: 'Aktiv', inactive: 'Inaktiv', error: 'Fehler' }
  return (
    <span className={`px-2.5 py-1 rounded-full text-xs font-medium ${colors[status as keyof typeof colors] || colors.inactive}`}>
      {labels[status as keyof typeof labels] || status}
    </span>
  )
}

export default function AgentDetailPage() {
  const params = useParams()
  const agentId = params.agentId as string

  const [agent, setAgent] = useState<AgentDetail | null>(null)
  const [loading, setLoading] = useState(true)
  const [activeTab, setActiveTab] = useState<'soul' | 'stats' | 'history'>('soul')
  const [editing, setEditing] = useState(false)
  const [editContent, setEditContent] = useState('')
  const [saving, setSaving] = useState(false)
  const [saveMessage, setSaveMessage] = useState('')
  const [backups, setBackups] = useState<BackupEntry[]>([])

  const loadAgent = useCallback(async () => {
    try {
      const res = await fetch(`/api/sdk/agents/${agentId}`)
      if (res.ok) {
        const data = await res.json()
        setAgent(data)
        if (!editing) setEditContent(data.soulContent)
      }
    } catch (err) {
      console.error('Failed to load agent:', err)
    } finally {
      setLoading(false)
    }
  }, [agentId, editing])

  const loadBackups = useCallback(async () => {
    try {
      const res = await fetch(`/api/sdk/agents/${agentId}/soul?history=true`)
      if (res.ok) {
        const data = await res.json()
        setBackups(data.backups || [])
      }
    } catch (err) {
      console.error('Failed to load backups:', err)
    }
  }, [agentId])

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

  useEffect(() => {
    if (activeTab === 'history') loadBackups()
  }, [activeTab, loadBackups])

  const handleSave = async () => {
    setSaving(true)
    setSaveMessage('')
    try {
      const res = await fetch(`/api/sdk/agents/${agentId}/soul`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ content: editContent }),
      })
      if (res.ok) {
        setSaveMessage('SOUL-Datei gespeichert')
        setEditing(false)
        await loadAgent()
      } else {
        const err = await res.json()
        setSaveMessage(`Fehler: ${err.error}`)
      }
    } catch {
      setSaveMessage('Speichern fehlgeschlagen')
    } finally {
      setSaving(false)
      setTimeout(() => setSaveMessage(''), 3000)
    }
  }

  const handleReset = () => {
    if (agent) {
      setEditContent(agent.soulContent)
      setEditing(false)
    }
  }

  if (loading) {
    return (
      <div className="p-8">
        <div className="animate-pulse space-y-4">
          <div className="h-8 bg-gray-200 rounded w-48" />
          <div className="h-64 bg-gray-200 rounded-xl" />
        </div>
      </div>
    )
  }

  if (!agent) {
    return (
      <div className="p-8">
        <p className="text-red-600">Agent nicht gefunden.</p>
        <Link href="/sdk/agents" className="text-purple-600 hover:underline mt-2 inline-block">
          Zurueck zur Uebersicht
        </Link>
      </div>
    )
  }

  return (
    <div className="p-8 max-w-5xl">
      {/* Header */}
      <div className="flex items-center gap-4 mb-6">
        <Link href="/sdk/agents" className="text-gray-400 hover:text-gray-600 transition-colors">
          <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
          </svg>
        </Link>
        <div
          className="w-12 h-12 rounded-xl flex items-center justify-center text-white"
          style={{ backgroundColor: agent.color }}
        >
          {agent.icon === 'shield' ? (
            <svg className="w-7 h-7" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}
                d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
            </svg>
          ) : (
            <svg className="w-7 h-7" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}
                d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
            </svg>
          )}
        </div>
        <div className="flex-1">
          <div className="flex items-center gap-3">
            <h1 className="text-2xl font-bold text-gray-900">{agent.name}</h1>
            <StatusBadge status={agent.status} />
          </div>
          <p className="text-sm text-gray-500">{agent.description}</p>
        </div>
      </div>

      {/* Stats Bar */}
      <div className="grid grid-cols-2 md:grid-cols-5 gap-4 mb-6">
        <div className="bg-white border border-gray-200 rounded-xl px-4 py-3">
          <div className="text-lg font-semibold text-gray-900">{agent.stats.sessionsToday}</div>
          <div className="text-xs text-gray-500">Sessions heute</div>
        </div>
        <div className="bg-white border border-gray-200 rounded-xl px-4 py-3">
          <div className="text-lg font-semibold text-gray-900">{agent.stats.avgResponseTime}</div>
          <div className="text-xs text-gray-500">Avg. Antwortzeit</div>
        </div>
        <div className="bg-white border border-gray-200 rounded-xl px-4 py-3">
          <div className="text-lg font-semibold text-gray-900">{agent.stats.successRate}</div>
          <div className="text-xs text-gray-500">Erfolgsrate</div>
        </div>
        <div className="bg-white border border-gray-200 rounded-xl px-4 py-3">
          <div className="text-lg font-semibold text-gray-900">v{agent.version}</div>
          <div className="text-xs text-gray-500">Version</div>
        </div>
        <div className="bg-white border border-gray-200 rounded-xl px-4 py-3">
          <div className="text-lg font-semibold text-gray-900">{agent.fileSize ? `${(agent.fileSize / 1024).toFixed(1)}k` : '—'}</div>
          <div className="text-xs text-gray-500">SOUL-Groesse</div>
        </div>
      </div>

      {/* Tabs */}
      <div className="flex border-b border-gray-200 mb-6">
        {[
          { id: 'soul' as const, label: 'SOUL-File' },
          { id: 'stats' as const, label: 'Live-Statistiken' },
          { id: 'history' as const, label: 'Aenderungshistorie' },
        ].map(tab => (
          <button
            key={tab.id}
            onClick={() => setActiveTab(tab.id)}
            className={`px-4 py-3 text-sm font-medium border-b-2 transition-colors ${
              activeTab === tab.id
                ? 'border-purple-600 text-purple-700'
                : 'border-transparent text-gray-500 hover:text-gray-700'
            }`}
          >
            {tab.label}
          </button>
        ))}
      </div>

      {/* Tab Content */}
      {activeTab === 'soul' && (
        <div>
          {/* Toolbar */}
          <div className="flex items-center justify-between mb-3">
            <div className="text-sm text-gray-500">
              {agent.updatedAt && `Zuletzt geaendert: ${new Date(agent.updatedAt).toLocaleString('de-DE')}`}
            </div>
            <div className="flex items-center gap-2">
              {saveMessage && (
                <span className={`text-sm ${saveMessage.startsWith('Fehler') ? 'text-red-600' : 'text-green-600'}`}>
                  {saveMessage}
                </span>
              )}
              {editing ? (
                <>
                  <button
                    onClick={handleReset}
                    className="px-3 py-1.5 text-sm text-gray-600 bg-white border border-gray-300 rounded-lg hover:bg-gray-50"
                  >
                    Abbrechen
                  </button>
                  <button
                    onClick={handleSave}
                    disabled={saving}
                    className="px-3 py-1.5 text-sm text-white bg-purple-600 rounded-lg hover:bg-purple-700 disabled:opacity-50"
                  >
                    {saving ? 'Speichern...' : 'Speichern'}
                  </button>
                </>
              ) : (
                <button
                  onClick={() => setEditing(true)}
                  className="px-3 py-1.5 text-sm text-purple-600 bg-purple-50 border border-purple-200 rounded-lg hover:bg-purple-100"
                >
                  Bearbeiten
                </button>
              )}
            </div>
          </div>

          {/* Editor */}
          <textarea
            value={editContent}
            onChange={(e) => setEditContent(e.target.value)}
            readOnly={!editing}
            className={`w-full h-[600px] font-mono text-sm p-4 border rounded-xl resize-none focus:outline-none ${
              editing
                ? 'border-purple-300 bg-white focus:ring-2 focus:ring-purple-200'
                : 'border-gray-200 bg-gray-50 cursor-default'
            }`}
            spellCheck={false}
          />
        </div>
      )}

      {activeTab === 'stats' && (
        <div className="bg-white border border-gray-200 rounded-xl p-8 text-center">
          <svg className="w-16 h-16 text-gray-300 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}
              d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
          </svg>
          <h3 className="text-lg font-medium text-gray-900 mb-2">Live-Statistiken</h3>
          <p className="text-gray-500">
            Detaillierte Echtzeit-Statistiken werden in einer zukuenftigen Version implementiert.
          </p>
        </div>
      )}

      {activeTab === 'history' && (
        <div>
          {backups.length === 0 ? (
            <div className="bg-white border border-gray-200 rounded-xl p-8 text-center">
              <svg className="w-16 h-16 text-gray-300 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}
                  d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              <h3 className="text-lg font-medium text-gray-900 mb-2">Keine Backups vorhanden</h3>
              <p className="text-gray-500">
                Backups werden automatisch beim Speichern von SOUL-Dateien erstellt.
              </p>
            </div>
          ) : (
            <div className="space-y-3">
              {backups.map((backup) => (
                <div key={backup.filename} className="bg-white border border-gray-200 rounded-xl px-5 py-4 flex items-center justify-between">
                  <div>
                    <div className="font-medium text-sm text-gray-900">
                      {new Date(backup.timestamp).toLocaleString('de-DE')}
                    </div>
                    <div className="text-xs text-gray-500 mt-0.5">
                      {(backup.size / 1024).toFixed(1)} KB — {backup.filename}
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    <div className="w-3 h-3 rounded-full bg-purple-200" />
                    <span className="text-xs text-gray-400">Backup</span>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  )
}
