'use client'

import { useState, useEffect, useCallback } from 'react'
import {
  WorkshopSession, Participant, WorkshopResponse, WorkshopComment,
  SessionStats, statusColors, statusLabels, typeLabels,
} from './types'
import { api } from './workshopApi'

export function SessionDetailView({ session, onBack, onRefresh }: {
  session: WorkshopSession
  onBack: () => void
  onRefresh: () => void
}) {
  const [participants, setParticipants] = useState<Participant[]>([])
  const [responses, setResponses] = useState<WorkshopResponse[]>([])
  const [comments, setComments] = useState<WorkshopComment[]>([])
  const [stats, setStats] = useState<SessionStats | null>(null)
  const [activeTab, setActiveTab] = useState<'participants' | 'responses' | 'comments'>('participants')
  const [loading, setLoading] = useState(true)

  const loadDetails = useCallback(async () => {
    setLoading(true)
    try {
      const [p, r, c, s] = await Promise.all([
        api<Participant[]>(`/${session.id}/participants`).catch(() => []),
        api<WorkshopResponse[]>(`/${session.id}/responses`).catch(() => []),
        api<WorkshopComment[]>(`/${session.id}/comments`).catch(() => []),
        api<SessionStats>(`/${session.id}/stats`).catch(() => null),
      ])
      setParticipants(Array.isArray(p) ? p : [])
      setResponses(Array.isArray(r) ? r : [])
      setComments(Array.isArray(c) ? c : [])
      setStats(s)
    } finally {
      setLoading(false)
    }
  }, [session.id])

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

  const handleLifecycle = async (action: 'start' | 'pause' | 'complete') => {
    try {
      await api(`/${session.id}/${action}`, { method: 'POST' })
      onRefresh()
    } catch (err) {
      console.error(`${action} error:`, err)
    }
  }

  const handleExport = async () => {
    try {
      const data = await api(`/${session.id}/export`)
      const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url; a.download = `workshop-${session.id}.json`; a.click()
      URL.revokeObjectURL(url)
    } catch (err) {
      console.error('Export error:', err)
    }
  }

  const roleColors: Record<string, string> = {
    FACILITATOR: 'bg-purple-100 text-purple-700',
    EXPERT: 'bg-blue-100 text-blue-700',
    STAKEHOLDER: 'bg-green-100 text-green-700',
    OBSERVER: 'bg-gray-100 text-gray-700',
  }

  return (
    <div>
      <button onClick={onBack} className="flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 mb-4">
        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
        </svg>
        Zurueck zur Uebersicht
      </button>

      <div className="bg-white rounded-xl border-2 border-gray-200 p-6 mb-6">
        <div className="flex items-start justify-between mb-4">
          <div>
            <h2 className="text-xl font-bold text-gray-900">{session.title}</h2>
            <p className="text-sm text-gray-500 mt-1">{session.description}</p>
          </div>
          <span className={`px-3 py-1 text-sm rounded-full ${statusColors[session.status]}`}>
            {statusLabels[session.status]}
          </span>
        </div>

        {stats && (
          <div className="grid grid-cols-4 gap-4 mb-4">
            <div className="bg-gray-50 rounded-lg p-3 text-center">
              <div className="text-2xl font-bold text-gray-900">{stats.total_participants}</div>
              <div className="text-xs text-gray-500">Teilnehmer</div>
            </div>
            <div className="bg-gray-50 rounded-lg p-3 text-center">
              <div className="text-2xl font-bold text-gray-900">{stats.active_participants}</div>
              <div className="text-xs text-gray-500">Aktiv</div>
            </div>
            <div className="bg-gray-50 rounded-lg p-3 text-center">
              <div className="text-2xl font-bold text-gray-900">{stats.total_responses}</div>
              <div className="text-xs text-gray-500">Antworten</div>
            </div>
            <div className="bg-gray-50 rounded-lg p-3 text-center">
              <div className="text-2xl font-bold text-purple-600">{stats.progress}%</div>
              <div className="text-xs text-gray-500">Fortschritt</div>
            </div>
          </div>
        )}

        <div className="flex items-center gap-3 mb-4">
          <span className="text-sm text-gray-500">Join-Code: <code className="bg-gray-100 px-2 py-0.5 rounded font-mono">{session.join_code}</code></span>
          <span className="text-sm text-gray-500">Typ: {typeLabels[session.session_type]}</span>
          <span className="text-sm text-gray-500">Schritt {session.current_step}/{session.total_steps}</span>
        </div>

        <div className="flex gap-2">
          {session.status === 'DRAFT' && (
            <button onClick={() => handleLifecycle('start')} className="px-3 py-1.5 text-sm bg-green-600 text-white rounded-lg hover:bg-green-700">Starten</button>
          )}
          {session.status === 'ACTIVE' && (
            <button onClick={() => handleLifecycle('pause')} className="px-3 py-1.5 text-sm bg-yellow-600 text-white rounded-lg hover:bg-yellow-700">Pausieren</button>
          )}
          {(session.status === 'ACTIVE' || session.status === 'PAUSED') && (
            <button onClick={() => handleLifecycle('complete')} className="px-3 py-1.5 text-sm bg-purple-600 text-white rounded-lg hover:bg-purple-700">Abschliessen</button>
          )}
          <button onClick={handleExport} className="px-3 py-1.5 text-sm border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50">Exportieren</button>
        </div>
      </div>

      <div className="flex gap-1 mb-4 bg-gray-100 p-1 rounded-lg">
        {(['participants', 'responses', 'comments'] as const).map(tab => (
          <button key={tab} onClick={() => setActiveTab(tab)}
            className={`flex-1 px-4 py-2 text-sm rounded-md transition-colors ${activeTab === tab ? 'bg-white text-gray-900 shadow-sm' : 'text-gray-600 hover:text-gray-900'}`}>
            {tab === 'participants' ? `Teilnehmer (${participants.length})` :
             tab === 'responses' ? `Antworten (${responses.length})` :
             `Kommentare (${comments.length})`}
          </button>
        ))}
      </div>

      {loading ? (
        <div className="text-center py-8 text-gray-500">Laden...</div>
      ) : (
        <>
          {activeTab === 'participants' && (
            <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
              <table className="w-full">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Name</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Rolle</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Abteilung</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Beigetreten</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-200">
                  {participants.map(p => (
                    <tr key={p.id} className="hover:bg-gray-50">
                      <td className="px-4 py-3">
                        <div className="font-medium text-gray-900">{p.name}</div>
                        <div className="text-xs text-gray-500">{p.email}</div>
                      </td>
                      <td className="px-4 py-3">
                        <span className={`px-2 py-0.5 text-xs rounded-full ${roleColors[p.role] || 'bg-gray-100 text-gray-700'}`}>
                          {p.role}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-sm text-gray-600">{p.department || '-'}</td>
                      <td className="px-4 py-3">
                        <span className={`inline-block w-2 h-2 rounded-full ${p.is_active ? 'bg-green-500' : 'bg-gray-300'}`} />
                      </td>
                      <td className="px-4 py-3 text-sm text-gray-500">
                        {new Date(p.joined_at).toLocaleDateString('de-DE')}
                      </td>
                    </tr>
                  ))}
                  {participants.length === 0 && (
                    <tr><td colSpan={5} className="px-4 py-8 text-center text-gray-500">Keine Teilnehmer</td></tr>
                  )}
                </tbody>
              </table>
            </div>
          )}

          {activeTab === 'responses' && (
            <div className="space-y-3">
              {responses.map(r => (
                <div key={r.id} className="bg-white rounded-lg border border-gray-200 p-4">
                  <div className="flex items-center justify-between mb-2">
                    <span className="text-sm font-medium text-gray-900">Schritt {r.step_number} / {r.field_id}</span>
                    <span className={`px-2 py-0.5 text-xs rounded-full ${
                      r.response_status === 'SUBMITTED' ? 'bg-green-100 text-green-700' :
                      r.response_status === 'REVIEWED' ? 'bg-purple-100 text-purple-700' :
                      'bg-gray-100 text-gray-700'
                    }`}>{r.response_status}</span>
                  </div>
                  <pre className="text-sm text-gray-600 bg-gray-50 p-2 rounded overflow-auto max-h-32">
                    {typeof r.value === 'string' ? r.value : JSON.stringify(r.value, null, 2)}
                  </pre>
                  <div className="text-xs text-gray-400 mt-2">
                    {new Date(r.created_at).toLocaleString('de-DE')}
                  </div>
                </div>
              ))}
              {responses.length === 0 && (
                <div className="text-center py-8 text-gray-500">Keine Antworten</div>
              )}
            </div>
          )}

          {activeTab === 'comments' && (
            <div className="space-y-3">
              {comments.map(c => (
                <div key={c.id} className={`bg-white rounded-lg border p-4 ${c.is_resolved ? 'border-green-200' : 'border-gray-200'}`}>
                  <div className="flex items-center justify-between mb-2">
                    {c.step_number != null && <span className="text-xs text-gray-500">Schritt {c.step_number}</span>}
                    {c.is_resolved && <span className="text-xs text-green-600">Geloest</span>}
                  </div>
                  <p className="text-sm text-gray-700">{c.text}</p>
                  <div className="text-xs text-gray-400 mt-2">
                    {new Date(c.created_at).toLocaleString('de-DE')}
                  </div>
                </div>
              ))}
              {comments.length === 0 && (
                <div className="text-center py-8 text-gray-500">Keine Kommentare</div>
              )}
            </div>
          )}
        </>
      )}
    </div>
  )
}
