'use client'

import { useState, useEffect } from 'react'
import { useParams } from 'next/navigation'
import Link from 'next/link'
import { AlertTriangle, FileText, Activity, History } from 'lucide-react'
import { mockAgentDetails, mockChangeLogs } from './_components/mock-data'
import {
  AgentHeader,
  AgentStatsBar,
  SoulTabContent,
  StatsTabContent,
  HistoryTabContent,
} from './_components'
import type { AgentDetail } from './_components'

type TabId = 'soul' | 'stats' | 'history'

const TABS: { id: TabId; label: string; icon: typeof FileText }[] = [
  { id: 'soul', label: 'SOUL-File', icon: FileText },
  { id: 'stats', label: 'Live-Statistiken', icon: Activity },
  { id: 'history', label: 'Aenderungshistorie', icon: History },
]

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

  const [agent, setAgent] = useState<AgentDetail | null>(null)
  const [editedContent, setEditedContent] = useState('')
  const [isEditing, setIsEditing] = useState(false)
  const [hasChanges, setHasChanges] = useState(false)
  const [saving, setSaving] = useState(false)
  const [activeTab, setActiveTab] = useState<TabId>('soul')

  useEffect(() => {
    const agentData = mockAgentDetails[agentId]
    if (agentData) {
      setAgent(agentData)
      setEditedContent(agentData.soulContent)
    }
  }, [agentId])

  const handleSave = async () => {
    setSaving(true)
    await new Promise(resolve => setTimeout(resolve, 1000))
    if (agent) {
      setAgent({ ...agent, soulContent: editedContent, updatedAt: new Date().toISOString() })
    }
    setHasChanges(false)
    setIsEditing(false)
    setSaving(false)
  }

  const handleReset = () => {
    if (agent) {
      setEditedContent(agent.soulContent)
      setHasChanges(false)
    }
  }

  const handleContentChange = (content: string) => {
    setEditedContent(content)
    setHasChanges(content !== agent?.soulContent)
  }

  if (!agent) {
    return (
      <div className="p-6 max-w-7xl mx-auto">
        <div className="text-center py-12">
          <AlertTriangle className="w-12 h-12 text-amber-500 mx-auto mb-4" />
          <h2 className="text-xl font-semibold text-gray-900 mb-2">Agent nicht gefunden</h2>
          <p className="text-gray-500 mb-4">Der Agent &quot;{agentId}&quot; existiert nicht.</p>
          <Link href="/ai/agents" className="text-teal-600 hover:text-teal-700">
            &larr; Zurueck zur Uebersicht
          </Link>
        </div>
      </div>
    )
  }

  return (
    <div className="p-6 max-w-7xl mx-auto">
      <AgentHeader agent={agent} />
      <AgentStatsBar agent={agent} />

      {/* Tabs */}
      <div className="bg-white border border-gray-200 rounded-xl overflow-hidden">
        <div className="border-b border-gray-200">
          <div className="flex">
            {TABS.map(({ id, label, icon: Icon }) => (
              <button
                key={id}
                onClick={() => setActiveTab(id)}
                className={`flex items-center gap-2 px-6 py-4 text-sm font-medium border-b-2 transition-colors ${
                  activeTab === id
                    ? 'border-teal-500 text-teal-600'
                    : 'border-transparent text-gray-500 hover:text-gray-700'
                }`}
              >
                <Icon className="w-4 h-4" />
                {label}
              </button>
            ))}
          </div>
        </div>

        <div className="p-6">
          {activeTab === 'soul' && (
            <SoulTabContent
              agent={agent}
              editedContent={editedContent}
              isEditing={isEditing}
              hasChanges={hasChanges}
              saving={saving}
              onContentChange={handleContentChange}
              onSave={handleSave}
              onReset={handleReset}
              onStartEditing={() => setIsEditing(true)}
            />
          )}
          {activeTab === 'stats' && <StatsTabContent />}
          {activeTab === 'history' && <HistoryTabContent changeLogs={mockChangeLogs} />}
        </div>
      </div>
    </div>
  )
}
