"use client";import { useEffect,useState } from "react";import { useRouter } from "next/navigation";import { LayoutDashboard,Users,CreditCard,Heart,MessagesSquare,Mic2,CalendarRange,BarChart3,Settings,LogOut,Search,Download,Send,Menu,X,TrendingUp } from "lucide-react";import { Tabs,TabsList,TabsTrigger,TabsContent } from "@/components/ui/tabs";
type Row=Record<string,string|number|null>;const nav=["Dashboard","Registrations","Payments","Conference Support","Communications","Speakers","Schedule","Reports","Settings"];
const icons=[LayoutDashboard,Users,CreditCard,Heart,MessagesSquare,Mic2,CalendarRange,BarChart3,Settings];
export function AdminDashboard(){const router=useRouter(),[view,setView]=useState("Dashboard"),[data,setData]=useState<any>(null),[q,setQ]=useState(""),[status,setStatus]=useState(""),[mobile,setMobile]=useState(false),[notice,setNotice]=useState("");const type=view==="Conference Support"?"support":view.toLowerCase();async function load(){const r=await fetch(`/api/admin/data?type=${encodeURIComponent(type)}&q=${encodeURIComponent(q)}&status=${encodeURIComponent(status)}`);if(r.status===401){router.push("/admin/login");return}setData(await r.json())}useEffect(()=>{load()},[view,status]);async function logout(){await fetch("/api/admin/auth",{method:"DELETE"});router.push("/admin/login")}return <div className="admin-shell"><aside className={mobile?"admin-side open":"admin-side"}><div className="admin-brand"><i>Ω</i><div><b>OMEGA FIRE</b><small>CONFERENCE PORTAL</small></div><button onClick={()=>setMobile(false)}><X/></button></div><nav>{nav.map((n,i)=>{const I=icons[i];return <button className={view===n?"active":""} key={n} onClick={()=>{setView(n);setMobile(false)}}><I/>{n}</button>})}</nav><button className="logout" onClick={logout}><LogOut/>Sign out</button></aside><main className="admin-main"><header><button className="mobile-admin" onClick={()=>setMobile(true)}><Menu/></button><div><span>OMEGA FIRE MINISTRIES</span><h1>{view}</h1></div><div className="admin-user"><span>Conference Team</span><b>OF</b></div></header>
{view==="Dashboard"&&<Dashboard data={data}/>} {(["Registrations","Payments","Conference Support"].includes(view))&&<Records type={type} rows={Array.isArray(data)?data:[]} q={q} setQ={setQ} status={status} setStatus={setStatus} load={load}/>} {view==="Communications"&&<Communications history={Array.isArray(data)?data:[]} onNotice={setNotice} reload={load}/>} {(["Speakers","Schedule","Reports","Settings"].includes(view))&&<Placeholder view={view}/>} {notice&&<div className="toast">{notice}<button onClick={()=>setNotice("")}>×</button></div>}</main></div>}
function Dashboard({data}:{data:any}){const m=data?.metrics||{};const cards=[["Total registrations",m.total_registrations||0,Users],["Confirmed",m.confirmed||0,TrendingUp],["Paid registrations",m.paid||0,CreditCard],["Pending / unpaid",m.unpaid||0,CalendarRange],["Successful payments",m.successful_payments||0,CreditCard],["Pending payments",m.pending_payments||0,CalendarRange],["Failed payments",m.failed_payments||0,CreditCard],["Refunded",m.refunded_payments||0,CreditCard],["Registration revenue",`$${Number(m.revenue||0).toLocaleString()}`,BarChart3],["Conference support",`$${Number(m.support_total||0).toLocaleString()}`,Heart]];return <div className="admin-content"><div className="metric-grid">{cards.map(([label,value,Icon]:any)=><article key={label}><div><span>{label}</span><b>{value}</b></div><Icon/></article>)}</div><section className="panel"><div className="panel-title"><div><h2>Recent registrations</h2><p>Latest attendee activity</p></div></div><AdminTable rows={data?.recent||[]} /></section></div>}
function Records({type,rows,q,setQ,status,setStatus,load}:{type:string,rows:Row[],q:string,setQ:(s:string)=>void,status:string,setStatus:(s:string)=>void,load:()=>void}){return <div className="admin-content"><div className="toolbar"><div className="search"><Search/><input value={q} onChange={e=>setQ(e.target.value)} onKeyDown={e=>e.key==="Enter"&&load()} placeholder="Search name, email or reference"/></div><select value={status} onChange={e=>setStatus(e.target.value)}><option value="">All statuses</option><option>confirmed</option><option>pending</option><option>successful</option><option>failed</option><option>refunded</option><option>cancelled</option></select><a className="btn admin-btn" href={`/api/admin/export?type=${type}`}><Download/>Export CSV</a></div><section className="panel"><div className="panel-title"><div><h2>{type==="support"?"Conference supporters":type}</h2><p>{rows.length} records shown</p></div></div><AdminTable rows={rows}/></section></div>}
function AdminTable({rows}:{rows:Row[]}){if(!rows.length)return <div className="empty-state">No records found.</div>;const preferred=["registration_number","first_name","last_name","supporter_name","email","supporter_email","amount","currency","purpose","status","payment_status","created_at"];const keys=preferred.filter(k=>rows.some(r=>k in r)).slice(0,7);return <div className="table-scroll"><table><thead><tr>{keys.map(k=><th key={k}>{k.replaceAll("_"," ")}</th>)}</tr></thead><tbody>{rows.map((r,i)=><tr key={String(r.id||i)}>{keys.map(k=><td key={k}>{k.includes("status")?<span className={`state ${r[k]}`}>{String(r[k]??"")}</span>:String(r[k]??"—")}</td>)}</tr>)}</tbody></table></div>}
function Communications({history,onNotice,reload}:{history:Row[],onNotice:(x:string)=>void,reload:()=>void}){async function send(e:React.FormEvent<HTMLFormElement>){e.preventDefault();if(!confirm("Send this message to the selected audience?"))return;const body=Object.fromEntries(new FormData(e.currentTarget));body.idempotencyKey=crypto.randomUUID();const r=await fetch("/api/admin/data",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(body)});const x=await r.json() as {sent?:number,failed?:number,error?:string};onNotice(r.ok?`${x.sent} sent, ${x.failed} failed`:x.error||"Message failed");reload()}return <div className="admin-content"><Tabs defaultValue="compose"><TabsList><TabsTrigger value="compose">Compose</TabsTrigger><TabsTrigger value="history">Message history</TabsTrigger></TabsList><TabsContent value="compose"><section className="panel composer"><h2>New communication</h2><form onSubmit={send}><div className="form-grid"><div className="field"><label>Channel</label><select name="channel"><option value="email">Email</option><option value="sms">SMS</option><option value="whatsapp">WhatsApp</option></select></div><div className="field"><label>Audience</label><select name="audience"><option value="all">All opted-in attendees</option><option value="confirmed">Confirmed attendees</option><option value="paid">Paid attendees</option><option value="unpaid">Unpaid / pending</option></select></div><div className="field full"><label>Subject</label><input name="subject" placeholder="Important conference update"/></div><div className="field full"><label>Message</label><textarea name="body" required placeholder="Hello {{first_name}}, ..."/></div></div><button className="btn btn-red"><Send/>Review and send</button></form></section></TabsContent><TabsContent value="history"><section className="panel"><AdminTable rows={history}/></section></TabsContent></Tabs></div>}
function Placeholder({view}:{view:string}){return <div className="admin-content"><section className="panel empty-state"><Settings/><h2>{view}</h2><p>This module is connected to the project database and prepared for conference content management. Use the configuration and seed scripts documented in the README to manage initial content.</p></section></div>}
