'use client'

import { useState, useEffect, useCallback } from 'react'
import {
  Portfolio, PortfolioItem, PortfolioStats, ActivityEntry, CompareResult,
  api, statusColors, statusLabels,
} from './PortfolioTypes'

const typeLabels: Record<string, string> = {
  ASSESSMENT: 'Assessment', ROADMAP: 'Roadmap', WORKSHOP: 'Workshop', DOCUMENT: 'Dokument',
}
const typeColors: Record<string, string> = {
  ASSESSMENT: 'bg-blue-100 text-blue-700', ROADMAP: 'bg-green-100 text-green-700',
  WORKSHOP: 'bg-purple-100 text-purple-700', DOCUMENT: 'bg-orange-100 text-orange-700',
}

export function PortfolioDetailView({ portfolio, onBack, onRefresh }: {
  portfolio: Portfolio
  onBack: () => void
  onRefresh: () => void
}) {
  const [items, setItems] = useState<PortfolioItem[]>([])
  const [activity, setActivity] = useState<ActivityEntry[]>([])
  const [stats, setStats] = useState<PortfolioStats | null>(null)
  const [activeTab, setActiveTab] = useState<'items' | 'activity' | 'compare'>('items')
  const [loading, setLoading] = useState(true)
  const [compareIds, setCompareIds] = useState('')
  const [compareResult, setCompareResult] = useState<CompareResult | null>(null)

  const loadDetails = useCallback(async () => {
    setLoading(true)
    try {
      const [i, a, s] = await Promise.all([
        api<PortfolioItem[]>(`/${portfolio.id}/items`).catch(() => []),
        api<ActivityEntry[]>(`/${portfolio.id}/activity`).catch(() => []),
        api<PortfolioStats>(`/${portfolio.id}/stats`).catch(() => null),
      ])
      setItems(Array.isArray(i) ? i : [])
      setActivity(Array.isArray(a) ? a : [])
      setStats(s)
    } finally {
      setLoading(false)
    }
  }, [portfolio.id])

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

  const handleSubmitReview = async () => {
    try { await api(`/${portfolio.id}/submit-review`, { method: 'POST' }); onRefresh() }
    catch (err) { console.error('Submit review error:', err) }
  }

  const handleApprove = async () => {
    try { await api(`/${portfolio.id}/approve`, { method: 'POST' }); onRefresh() }
    catch (err) { console.error('Approve error:', err) }
  }

  const handleRecalculate = async () => {
    try { await api(`/${portfolio.id}/recalculate`, { method: 'POST' }); loadDetails(); onRefresh() }
    catch (err) { console.error('Recalculate error:', err) }
  }

  const handleCompare = async () => {
    const ids = compareIds.split(',').map(s => s.trim()).filter(Boolean)
    if (ids.length < 1) return
    try {
      const result = await api<CompareResult>('/compare', {
        method: 'POST',
        body: JSON.stringify({ portfolio_ids: [portfolio.id, ...ids] }),
      })
      setCompareResult(result)
    } catch (err) { console.error('Compare error:', err) }
  }

  const handleRemoveItem = async (itemId: string) => {
    try {
      await api(`/${portfolio.id}/items/${itemId}`, { method: 'DELETE' })
      setItems(prev => prev.filter(i => i.id !== itemId))
    } catch (err) { console.error('Remove item error:', err) }
  }

  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">{portfolio.name}</h2>
            <p className="text-sm text-gray-500 mt-1">{portfolio.description}</p>
          </div>
          <span className={`px-3 py-1 text-sm rounded-full ${statusColors[portfolio.status]}`}>
            {statusLabels[portfolio.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-purple-600">{stats.compliance_score}%</div>
              <div className="text-xs text-gray-500">Compliance</div>
            </div>
            <div className="bg-gray-50 rounded-lg p-3 text-center">
              <div className="text-2xl font-bold text-gray-900">{stats.avg_risk_score.toFixed(1)}</div>
              <div className="text-xs text-gray-500">Risiko-Score</div>
            </div>
            <div className="bg-gray-50 rounded-lg p-3 text-center">
              <div className="text-2xl font-bold text-gray-900">{stats.total_items}</div>
              <div className="text-xs text-gray-500">Items</div>
            </div>
            <div className="bg-gray-50 rounded-lg p-3 text-center">
              <div className="text-2xl font-bold text-red-600">{portfolio.high_risk_count}</div>
              <div className="text-xs text-gray-500">Hoch-Risiko</div>
            </div>
          </div>
        )}

        <div className="flex gap-2">
          {portfolio.status === 'ACTIVE' && (
            <button onClick={handleSubmitReview} className="px-3 py-1.5 text-sm bg-yellow-600 text-white rounded-lg hover:bg-yellow-700">
              Zur Pruefung einreichen
            </button>
          )}
          {portfolio.status === 'REVIEW' && (
            <button onClick={handleApprove} className="px-3 py-1.5 text-sm bg-green-600 text-white rounded-lg hover:bg-green-700">
              Genehmigen
            </button>
          )}
          <button onClick={handleRecalculate} className="px-3 py-1.5 text-sm border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50">
            Metriken neu berechnen
          </button>
        </div>
      </div>

      {/* Tabs */}
      <div className="flex gap-1 mb-4 bg-gray-100 p-1 rounded-lg">
        {(['items', 'activity', 'compare'] 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 === 'items' ? `Items (${items.length})` : tab === 'activity' ? 'Aktivitaet' : 'Vergleich'}
          </button>
        ))}
      </div>

      {loading ? (
        <div className="text-center py-8 text-gray-500">Laden...</div>
      ) : (
        <>
          {activeTab === 'items' && (
            <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
              <table className="w-full">
                <thead className="bg-gray-50">
                  <tr>
                    {['Titel', 'Typ', 'Status', 'Risiko', 'Aktion'].map(h => (
                      <th key={h} className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-200">
                  {items.map(item => (
                    <tr key={item.id} className="hover:bg-gray-50">
                      <td className="px-4 py-3">
                        <div className="font-medium text-gray-900">{item.title}</div>
                        {item.notes && <div className="text-xs text-gray-500 truncate max-w-xs">{item.notes}</div>}
                      </td>
                      <td className="px-4 py-3">
                        <span className={`px-2 py-0.5 text-xs rounded-full ${typeColors[item.item_type] || 'bg-gray-100 text-gray-700'}`}>
                          {typeLabels[item.item_type] || item.item_type}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-sm text-gray-600">{item.status}</td>
                      <td className="px-4 py-3">
                        <span className={`text-sm font-medium ${
                          item.risk_score >= 7 ? 'text-red-600' : item.risk_score >= 4 ? 'text-yellow-600' : 'text-green-600'
                        }`}>{item.risk_score.toFixed(1)}</span>
                      </td>
                      <td className="px-4 py-3">
                        <button onClick={() => handleRemoveItem(item.id)} className="text-xs text-red-500 hover:text-red-700">Entfernen</button>
                      </td>
                    </tr>
                  ))}
                  {items.length === 0 && (
                    <tr><td colSpan={5} className="px-4 py-8 text-center text-gray-500">Keine Items</td></tr>
                  )}
                </tbody>
              </table>
            </div>
          )}

          {activeTab === 'activity' && (
            <div className="space-y-3">
              {activity.map((a, i) => (
                <div key={i} className="bg-white rounded-lg border border-gray-200 p-4 flex items-center gap-4">
                  <div className={`w-8 h-8 rounded-full flex items-center justify-center text-white text-xs ${
                    a.action === 'added' ? 'bg-green-500' : a.action === 'removed' ? 'bg-red-500' : 'bg-blue-500'
                  }`}>
                    {a.action === 'added' ? '+' : a.action === 'removed' ? '-' : '~'}
                  </div>
                  <div className="flex-1">
                    <div className="text-sm text-gray-900">
                      <span className="font-medium">{a.item_title || a.item_id}</span> {a.action}
                    </div>
                    <div className="text-xs text-gray-500">{a.item_type}</div>
                  </div>
                  <div className="text-xs text-gray-400">{new Date(a.timestamp).toLocaleString('de-DE')}</div>
                </div>
              ))}
              {activity.length === 0 && <div className="text-center py-8 text-gray-500">Keine Aktivitaet</div>}
            </div>
          )}

          {activeTab === 'compare' && (
            <div className="bg-white rounded-xl border border-gray-200 p-6">
              <h3 className="text-lg font-semibold text-gray-900 mb-4">Portfolio-Vergleich</h3>
              <div className="flex gap-3 mb-4">
                <input type="text" value={compareIds} onChange={e => setCompareIds(e.target.value)}
                  className="flex-1 px-3 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500"
                  placeholder="Portfolio-IDs (kommagetrennt)" />
                <button onClick={handleCompare}
                  className="px-4 py-2 bg-purple-600 text-white text-sm rounded-lg hover:bg-purple-700">
                  Vergleichen
                </button>
              </div>
              {compareResult && (
                <div className="overflow-x-auto">
                  <table className="w-full">
                    <thead className="bg-gray-50">
                      <tr>
                        {['Portfolio', 'Risiko-Score', 'Compliance', 'Items'].map(h => (
                          <th key={h} className="px-4 py-3 text-left text-xs font-medium text-gray-500">{h}</th>
                        ))}
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-200">
                      {compareResult.portfolios?.map(p => (
                        <tr key={p.id}>
                          <td className="px-4 py-3 font-medium text-gray-900">{p.name}</td>
                          <td className="px-4 py-3 text-center">{compareResult.risk_scores?.[p.id]?.toFixed(1) ?? '-'}</td>
                          <td className="px-4 py-3 text-center">{compareResult.compliance_scores?.[p.id] ?? '-'}%</td>
                          <td className="px-4 py-3 text-center">{compareResult.item_counts?.[p.id] ?? '-'}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                  {compareResult.common_items?.length > 0 && (
                    <div className="mt-4 p-3 bg-gray-50 rounded-lg">
                      <div className="text-xs font-medium text-gray-500 mb-1">Gemeinsame Items: {compareResult.common_items.length}</div>
                    </div>
                  )}
                </div>
              )}
            </div>
          )}
        </>
      )}
    </div>
  )
}
