'use client'

import { useState, useMemo } from'react'
import { Search, RefreshCw } from'lucide-react'

export interface EmailEntry {
 id: string
 to_email: string
 template: string
 status:'pending'|'sent'|'failed'
 created_at: string
 sent_at: string | null
 error: string | null
}

interface Props {
 initialEntries: EmailEntry[]
}

const PAGE_SIZE = 50

function StatusBadge({ status }: { status: string }) {
 const cfg: Record<string, { cls: string; label: string }> = {
 pending: { cls:'bg-amber-100 text-amber-800', label:'Ausstehend'},
 sent: { cls:'bg-green-100 text-green-800', label:'Gesendet'},
 failed: { cls:'bg-red-100 text-red-800', label:'Fehler'},
 }
 const { cls, label } = cfg[status] ?? { cls:'bg-muted text-foreground', label: status }
 return (
 <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${cls}`}>
 {label}
 </span>
 )
}

function formatDate(iso: string): string {
 return new Date(iso).toLocaleString('de-DE', {
 day:'2-digit',
 month:'2-digit',
 year:'numeric',
 hour:'2-digit',
 minute:'2-digit',
 })
}

export default function EmailQueueClient({ initialEntries }: Props) {
 const [entries, setEntries] = useState<EmailEntry[]>(initialEntries)
 const [search, setSearch] = useState('')
 const [filterStatus, setFilterStatus] = useState('')
 const [filterTemplate, setFilterTemplate] = useState('')
 const [filterFrom, setFilterFrom] = useState('')
 const [filterTo, setFilterTo] = useState('')
 const [page, setPage] = useState(1)
 const [retryingId, setRetryingId] = useState<string | null>(null)

 const templateOptions = useMemo(() => {
 const set = new Set<string>()
 entries.forEach((e) => set.add(e.template))
 return Array.from(set).sort()
 }, [entries])

 const filtered = useMemo(() => {
 const q = search.toLowerCase()
 return entries.filter((e) => {
 if (filterStatus && e.status !== filterStatus) return false
 if (filterTemplate && e.template !== filterTemplate) return false
 if (filterFrom && e.created_at < filterFrom) return false
 if (filterTo && e.created_at > filterTo +'T23:59:59') return false
 if (q && !e.to_email.toLowerCase().includes(q) && !e.template.toLowerCase().includes(q)) return false
 return true
 })
 }, [entries, search, filterStatus, filterTemplate, filterFrom, filterTo])

 const paginated = filtered.slice(0, page * PAGE_SIZE)
 const hasMore = paginated.length < filtered.length

 async function handleRetry(id: string) {
 setRetryingId(id)
 const res = await fetch('/api/admin/emails/retry', {
 method:'POST',
 headers: {'Content-Type':'application/json'},
 body: JSON.stringify({ id }),
 })
 if (res.ok) {
 const { entry } = await res.json() as { entry: EmailEntry }
 setEntries((prev) => prev.map((e) => e.id === id ? entry : e))
 }
 setRetryingId(null)
 }

 return (
 <div className="space-y-5">
 {/* Header */}
 <div>
 <h1 className="text-xl font-bold text-foreground">E-Mail Queue</h1>
 <p className="text-sm text-muted-foreground mt-0.5">{filtered.length} Einträge</p>
 </div>

 {/* Filters */}
 <div className="flex flex-wrap gap-3">
 <div className="relative flex-1 min-w-48">
 <Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"/>
 <input
 type="text"
 value={search}
 onChange={(e) => { setSearch(e.target.value); setPage(1) }}
 placeholder="Empfänger oder Vorlage suchen…"
 className="w-full h-9 pl-9 pr-3 rounded-lg border border-border bg-card text-sm text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary"
 />
 </div>
 <select
 value={filterStatus}
 onChange={(e) => { setFilterStatus(e.target.value); setPage(1) }}
 className="h-9 px-3 rounded-lg border border-border bg-card text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
 >
 <option value="">Alle Status</option>
 <option value="pending">Ausstehend</option>
 <option value="sent">Gesendet</option>
 <option value="failed">Fehler</option>
 </select>
 <select
 value={filterTemplate}
 onChange={(e) => { setFilterTemplate(e.target.value); setPage(1) }}
 className="h-9 px-3 rounded-lg border border-border bg-card text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
 >
 <option value="">Alle Vorlagen</option>
 {templateOptions.map((t) => (
 <option key={t} value={t}>{t}</option>
 ))}
 </select>
 <input
 type="date"
 value={filterFrom}
 onChange={(e) => { setFilterFrom(e.target.value); setPage(1) }}
 className="h-9 px-3 rounded-lg border border-border bg-card text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
 />
 <input
 type="date"
 value={filterTo}
 onChange={(e) => { setFilterTo(e.target.value); setPage(1) }}
 className="h-9 px-3 rounded-lg border border-border bg-card text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
 />
 </div>

 {/* Table */}
 <div className="bg-card rounded-xl border border-border overflow-hidden">
 <div className="overflow-x-auto">
 <table className="w-full text-sm">
 <thead>
 <tr className="border-b border-border bg-background">
 <th className="text-left px-4 py-3 font-semibold text-muted-foreground text-xs uppercase tracking-wider">Empfänger</th>
 <th className="text-left px-4 py-3 font-semibold text-muted-foreground text-xs uppercase tracking-wider">Vorlage</th>
 <th className="text-left px-4 py-3 font-semibold text-muted-foreground text-xs uppercase tracking-wider">Status</th>
 <th className="text-left px-4 py-3 font-semibold text-muted-foreground text-xs uppercase tracking-wider">Erstellt</th>
 <th className="text-left px-4 py-3 font-semibold text-muted-foreground text-xs uppercase tracking-wider hidden md:table-cell">Gesendet</th>
 <th className="text-left px-4 py-3 font-semibold text-muted-foreground text-xs uppercase tracking-wider hidden lg:table-cell">Fehler</th>
 <th className="text-right px-4 py-3 font-semibold text-muted-foreground text-xs uppercase tracking-wider">Aktionen</th>
 </tr>
 </thead>
 <tbody className="divide-y divide-border">
 {paginated.length === 0 && (
 <tr>
 <td colSpan={7} className="px-4 py-10 text-center text-muted-foreground text-sm">
 Keine Einträge gefunden.
 </td>
 </tr>
 )}
 {paginated.map((entry) => (
 <tr key={entry.id} className="hover:bg-background transition-colors">
 <td className="px-4 py-3 text-foreground font-medium">{entry.to_email}</td>
 <td className="px-4 py-3 text-muted-foreground font-mono text-xs">{entry.template}</td>
 <td className="px-4 py-3"><StatusBadge status={entry.status} /></td>
 <td className="px-4 py-3 text-muted-foreground text-xs whitespace-nowrap">{formatDate(entry.created_at)}</td>
 <td className="px-4 py-3 text-muted-foreground text-xs whitespace-nowrap hidden md:table-cell">
 {entry.sent_at ? formatDate(entry.sent_at) :'—'}
 </td>
 <td className="px-4 py-3 text-destructive text-xs hidden lg:table-cell max-w-xs truncate">
 {entry.error ??'—'}
 </td>
 <td className="px-4 py-3 text-right">
 {entry.status ==='failed'&& (
 <button
 onClick={() => void handleRetry(entry.id)}
 disabled={retryingId === entry.id}
 title="Erneut versuchen"
 className="inline-flex items-center gap-1.5 h-8 px-3 rounded-lg border border-border text-xs text-foreground hover:bg-background disabled:opacity-50 transition-colors"
 >
 <RefreshCw size={12} className={retryingId === entry.id ?'animate-spin':''} />
 Wiederholen
 </button>
 )}
 </td>
 </tr>
 ))}
 </tbody>
 </table>
 </div>
 </div>

 {/* Load more */}
 {hasMore && (
 <div className="flex justify-center">
 <button
 onClick={() => setPage((p) => p + 1)}
 className="h-10 px-6 border border-border bg-card text-foreground rounded-lg text-sm font-medium hover:bg-background transition-colors"
 >
 Mehr laden
 </button>
 </div>
 )}
 </div>
 )
}
