"use client";
import {useCallback,useEffect,useRef,useState} from "react";import Link from "next/link";import {createClient} from "@/lib/supabase/client";import type{ServiceRequest,Restaurant}from"@/lib/types";import {BellRing,Check,Clock3,Volume2,VolumeX,LogOut,Settings,Radio,Filter,Play,RefreshCw,LoaderCircle,Utensils}from"lucide-react";
export default function Dashboard(){const db=createClient();const [venue,setVenue]=useState<Restaurant|null>(null);const [rows,setRows]=useState<ServiceRequest[]>([]);const [filter,setFilter]=useState('active');const [tableFilter,setTableFilter]=useState('all');const [sound,setSound]=useState(false);const [loading,setLoading]=useState(true);const [busy,setBusy]=useState<string|null>(null);const [error,setError]=useState('');const seen=useRef(new Set<string>());const ctx=useRef<AudioContext|null>(null);
const chime=useCallback(()=>{if(!sound)return;try{ctx.current??=new AudioContext();const c=ctx.current;c.resume();[660,880].forEach((hz,i)=>{const o=c.createOscillator(),g=c.createGain();o.frequency.value=hz;o.type='sine';g.gain.setValueAtTime(.0001,c.currentTime+i*.14);g.gain.exponentialRampToValueAtTime(.12,c.currentTime+i*.14+.025);g.gain.exponentialRampToValueAtTime(.0001,c.currentTime+i*.14+.23);o.connect(g);g.connect(c.destination);o.start(c.currentTime+i*.14);o.stop(c.currentTime+i*.14+.25)})}catch{}} ,[sound]);
const load=useCallback(async(initial=false)=>{const {data:{user}}=await db.auth.getUser();if(!user){location.href='/login';return}const {data:m,error:me}=await db.from('restaurant_memberships').select('restaurant_id,role,restaurants(id,name,slug,logo_url,brand_color,welcome_message)').eq('user_id',user.id).eq('active',true).limit(1).maybeSingle();if(me||!m){setError(me?.message||'Your account is not linked to a restaurant yet. Ask an admin to add you.');setLoading(false);return}const v=(Array.isArray(m.restaurants)?m.restaurants[0]:m.restaurants) as Restaurant;setVenue(v);const {data,error}=await db.from('service_requests').select('id,restaurant_id,table_id,service_type_id,request_type,message,status,created_at,acknowledged_at,completed_at,restaurant_tables(label)').eq('restaurant_id',v.id).order('created_at',{ascending:true}).limit(250);if(error)setError(error.message);else{const clean=(data||[]).map((x:any)=>({...x,table:x.restaurant_tables}));if(!initial){clean.forEach(x=>{if(!seen.current.has(x.id)){seen.current.add(x.id);if(x.status==='new')chime()}})}else clean.forEach(x=>seen.current.add(x.id));setRows(clean)}setLoading(false)},[db,chime]);
useEffect(()=>{load(true);const channel=db.channel('staff-live-requests').on('postgres_changes',{event:'INSERT',schema:'public',table:'service_requests'},payload=>{const r=payload.new as ServiceRequest;seen.current.add(r.id);setRows(prev=>[...prev,r].sort((a,b)=>a.created_at.localeCompare(b.created_at)));chime()}).on('postgres_changes',{event:'UPDATE',schema:'public',table:'service_requests'},payload=>{const r=payload.new as ServiceRequest;setRows(prev=>prev.map(x=>x.id===r.id?{...x,...r}:x))}).subscribe();const timer=setInterval(()=>{load(false)},60000);return()=>{db.removeChannel(channel);clearInterval(timer)}},[db,load,chime]);
async function status(id:string,next:'acknowledged'|'completed'){setBusy(id);setError('');const field=next==='acknowledged'?{status:next,acknowledged_at:new Date().toISOString()}:{status:next,completed_at:new Date().toISOString()};const {error}=await db.from('service_requests').update(field).eq('id',id);if(error)setError(error.message);else setRows(rs=>rs.map(r=>r.id===id?{...r,...field}:r));setBusy(null)}
const active=rows.filter(r=>r.status!=='completed');const completed=rows.filter(r=>r.status==='completed'&&new Date(r.created_at).toDateString()===new Date().toDateString());const tables=Array.from(new Set(rows.map(r=>r.table?.label).filter(Boolean))) as string[];const shown=rows.filter(r=>(filter==='active'?r.status!=='completed':filter==='completed'?r.status==='completed':true)&&(tableFilter==='all'||r.table?.label===tableFilter));const oldest=active[0];
return <main className="min-h-screen"><header className="sticky top-0 z-10 border-b border-[#e7ebe4] bg-[#f5f6f2]/95 backdrop-blur"><div className="mx-auto flex max-w-7xl items-center justify-between px-5 py-4"><div className="flex items-center gap-3"><span className="grid h-10 w-10 place-items-center rounded-xl bg-green text-white"><Radio size={19}/></span><div><div className="display font-bold">{venue?.name||'Service desk'}</div><div className="flex items-center gap-1.5 text-xs text-muted"><span className="h-1.5 w-1.5 rounded-full bg-[#75a96a]"/> Live service overview</div></div></div><div className="flex items-center gap-2"><button onClick={()=>setSound(v=>!v)} className={`btn text-sm ${sound?'bg-[#e6f1e1] text-green':'btn-quiet'}`} title={sound?'Mute notifications':'Enable notifications'}>{sound?<Volume2 size={17}/>:<VolumeX size={17}/>}<span className="hidden sm:inline">Sound {sound?'on':'off'}</span></button><button onClick={chime} className="btn btn-quiet text-sm" title="Test notification sound"><Play size={15}/><span className="hidden sm:inline">Test</span></button><Link href="/admin" className="btn btn-quiet text-sm"><Settings size={16}/><span className="hidden sm:inline">Manage</span></Link><button onClick={async()=>{await db.auth.signOut();location.href='/login'}} className="btn btn-quiet px-3" title="Sign out"><LogOut size={16}/></button></div></div></header>
<div className="mx-auto max-w-7xl px-5 py-8"><div className="mb-7 flex flex-wrap items-end justify-between gap-4"><div><div className="text-xs font-bold uppercase tracking-[.16em] text-muted">Restaurant operations</div><h1 className="display mt-2 text-3xl font-bold">Service requests</h1><p className="mt-1 text-sm text-muted">Keep every table moving, one request at a time.</p></div><div className="flex gap-3"><div className="card min-w-28 px-4 py-3"><div className="text-xs text-muted">Active</div><div className="display mt-1 text-2xl font-bold">{active.length}</div></div><div className="card min-w-28 px-4 py-3"><div className="text-xs text-muted">Completed today</div><div className="display mt-1 text-2xl font-bold">{completed.length}</div></div></div></div>{error&&<div role="alert" className="mb-5 rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700">{error}</div>}<div className="mb-4 flex flex-wrap items-center justify-between gap-3"><div className="flex rounded-xl border border-[#e4e8e1] bg-white p-1">{[['active','Active'],['all','All requests'],['completed','Completed']].map(([k,n])=><button key={k} onClick={()=>setFilter(k)} className={`rounded-lg px-3 py-2 text-sm font-semibold ${filter===k?'bg-[#edf3e9] text-green':'text-muted'}`}>{n}</button>)}</div><div className="flex items-center gap-2"><Filter size={16} className="text-muted"/><select aria-label="Filter by table" className="field !w-auto !py-2 text-sm" value={tableFilter} onChange={e=>setTableFilter(e.target.value)}><option value="all">All tables</option>{tables.map(t=><option key={t}>{t}</option>)}</select><button onClick={()=>load(false)} className="btn btn-quiet px-3" title="Refresh"><RefreshCw size={16}/></button></div></div>
<div className="space-y-3">{loading?<div className="card grid min-h-48 place-items-center text-muted"><LoaderCircle className="animate-spin"/></div>:shown.length===0?<div className="card grid min-h-64 place-items-center p-8 text-center"><div><div className="mx-auto grid h-14 w-14 place-items-center rounded-2xl bg-lime text-green"><Check size={24}/></div><h2 className="display mt-4 text-xl font-bold">All caught up</h2><p className="mt-1 text-sm text-muted">New table requests will appear here as they arrive.</p></div></div>:shown.map(r=>{const age=Math.max(0,Math.floor((Date.now()-new Date(r.created_at).getTime())/60000));return <article key={r.id} className={`card flex flex-col gap-4 p-4 sm:flex-row sm:items-center sm:justify-between sm:p-5 ${r.status==='new'?'border-l-4 border-l-[#83a96b] bg-[#fcfdfb]':''}`}><div className="flex items-start gap-4"><div className={`grid h-14 w-14 shrink-0 place-items-center rounded-2xl text-sm font-bold ${r.status==='new'?'bg-[#e8f1e3] text-green':'bg-[#f0f2ed] text-ink'}`}><Utensils size={17}/><span className="text-[10px]">{r.table?.label||'Table'}</span></div><div><div className="flex flex-wrap items-center gap-2"><h2 className="font-bold">{r.request_type}</h2><span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${r.status==='new'?'bg-[#e8f1e3] text-green':r.status==='acknowledged'?'bg-[#f7eedb] text-[#8c6b2c]':'bg-[#edf0ec] text-muted'}`}>{r.status==='new'?'New':r.status==='acknowledged'?'Acknowledged':'Completed'}</span></div>{r.message&&<p className="mt-1 text-sm text-ink">“{r.message}”</p>}<div className="mt-2 flex flex-wrap gap-3 text-xs text-muted"><span>{new Date(r.created_at).toLocaleTimeString([],{hour:'2-digit',minute:'2-digit'})}</span><span className="flex items-center gap-1"><Clock3 size={13}/>{age<1?'Just now':`${age} min waiting`}</span></div></div></div><div className="flex gap-2 sm:pl-4">{r.status==='new'&&<button disabled={busy===r.id} onClick={()=>status(r.id,'acknowledged')} className="btn btn-quiet flex-1 text-sm sm:flex-none">Acknowledge</button>}{r.status!=='completed'&&<button disabled={busy===r.id} onClick={()=>status(r.id,'completed')} className="btn btn-primary flex-1 text-sm sm:flex-none">{busy===r.id?<LoaderCircle size={16} className="animate-spin"/>:<Check size={16}/>}Complete</button>}</div></article>})}</div><div className="mt-6 text-center text-xs text-muted">{oldest?`Oldest active request · ${oldest.table?.label||'Table'} · ${Math.max(0,Math.floor((Date.now()-new Date(oldest.created_at).getTime())/60000))} min`: 'You’re up to date'}</div></div></main>}
