'use client'

import { useState } from 'react'
import type { DocumentReview, ReviewStats } from '../_types'
import { STATUS_CONFIG, ROLE_ICONS } from '../_types'

interface ReviewListProps {
  reviews: DocumentReview[]
  stats: ReviewStats
  loading: boolean
  statusFilter: string | null
  onFilterChange: (status: string | null) => void
  onApprove: (id: string) => Promise<void>
  onReject: (id: string, comment: string) => Promise<void>
  onSendNotification: (id: string) => Promise<void>
}

export function ReviewList({
  reviews, stats, loading, statusFilter, onFilterChange,
  onApprove, onReject, onSendNotification,
}: ReviewListProps) {
  const [rejectId, setRejectId] = useState<string | null>(null)
  const [rejectComment, setRejectComment] = useState('')
  const [processing, setProcessing] = useState<string | null>(null)

  const total = Object.values(stats).reduce((s, n) => s + (n || 0), 0)

  const handleApprove = async (id: string) => {
    setProcessing(id)
    try { await onApprove(id) } finally { setProcessing(null) }
  }

  const handleReject = async () => {
    if (!rejectId || !rejectComment.trim()) return
    setProcessing(rejectId)
    try {
      await onReject(rejectId, rejectComment)
      setRejectId(null)
      setRejectComment('')
    } finally { setProcessing(null) }
  }

  return (
    <div className="space-y-4">
      {/* Stats */}
      <div className="flex gap-3 flex-wrap">
        <button onClick={() => onFilterChange(null)}
          className={`px-3 py-1 text-xs rounded-full border ${!statusFilter ? 'bg-purple-100 border-purple-300 text-purple-700' : 'bg-white border-gray-200 text-gray-600 hover:border-gray-300'}`}>
          Alle ({total})
        </button>
        {Object.entries(STATUS_CONFIG).map(([key, cfg]) => (
          <button key={key} onClick={() => onFilterChange(key === statusFilter ? null : key)}
            className={`px-3 py-1 text-xs rounded-full border ${statusFilter === key ? cfg.color + ' border-current' : 'bg-white border-gray-200 text-gray-600 hover:border-gray-300'}`}>
            {cfg.label} ({stats[key as keyof ReviewStats] || 0})
          </button>
        ))}
      </div>

      {/* List */}
      {loading ? (
        <div className="text-center py-8 text-gray-400">Lade Reviews...</div>
      ) : reviews.length === 0 ? (
        <div className="text-center py-8 text-gray-400">Keine Reviews vorhanden</div>
      ) : (
        <div className="space-y-2">
          {reviews.map(review => {
            const cfg = STATUS_CONFIG[review.status] || STATUS_CONFIG.pending
            return (
              <div key={review.id} className="bg-white border border-gray-200 rounded-lg p-4 flex items-center gap-4">
                <span className="text-xl">{ROLE_ICONS[review.reviewer_role_key] || '\u{1F464}'}</span>
                <div className="flex-1 min-w-0">
                  <div className="font-medium text-sm text-gray-900 truncate">{review.document_title}</div>
                  <div className="text-xs text-gray-500">
                    {review.reviewer_name || review.reviewer_role_key}
                    {review.submitted_at && ` — ${new Date(review.submitted_at).toLocaleDateString('de-DE')}`}
                  </div>
                </div>
                <span className={`px-2 py-0.5 text-[10px] font-medium rounded-full ${cfg.color}`}>{cfg.label}</span>
                {review.status === 'pending' && (
                  <button onClick={() => onSendNotification(review.id)}
                    className="px-2 py-1 text-xs bg-blue-50 text-blue-600 rounded hover:bg-blue-100">
                    E-Mail
                  </button>
                )}
                {(review.status === 'pending' || review.status === 'in_review') && (
                  <div className="flex gap-1">
                    <button onClick={() => handleApprove(review.id)} disabled={processing === review.id}
                      className="px-2 py-1 text-xs bg-green-50 text-green-600 rounded hover:bg-green-100 disabled:opacity-50">
                      Freigeben
                    </button>
                    <button onClick={() => setRejectId(review.id)}
                      className="px-2 py-1 text-xs bg-red-50 text-red-600 rounded hover:bg-red-100">
                      Ablehnen
                    </button>
                  </div>
                )}
                {review.status === 'rejected' && review.review_comment && (
                  <span className="text-xs text-red-500 max-w-[200px] truncate" title={review.review_comment}>
                    {review.review_comment}
                  </span>
                )}
              </div>
            )
          })}
        </div>
      )}

      {/* Reject Dialog */}
      {rejectId && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
          <div className="bg-white rounded-xl p-6 w-full max-w-md shadow-2xl">
            <h3 className="text-lg font-semibold mb-3">Dokument ablehnen</h3>
            <textarea value={rejectComment} onChange={e => setRejectComment(e.target.value)}
              placeholder="Grund fuer die Ablehnung..." rows={3}
              className="w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-1 focus:ring-red-500" />
            <div className="flex justify-end gap-2 mt-4">
              <button onClick={() => { setRejectId(null); setRejectComment('') }}
                className="px-4 py-2 text-sm text-gray-600 hover:bg-gray-100 rounded-lg">Abbrechen</button>
              <button onClick={handleReject} disabled={!rejectComment.trim() || processing === rejectId}
                className="px-4 py-2 text-sm bg-red-600 text-white rounded-lg hover:bg-red-700 disabled:opacity-50">
                Ablehnen
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
