'use client';
import {useEffect,useMemo,useState} from 'react';
import Link from 'next/link';
import {ArrowLeft,Code2,GitBranch,RotateCcw,Save,ShieldCheck} from 'lucide-react';
import {toast} from 'sonner';
import {WorkspaceShell} from '@/components/workspace-shell';
import {Button} from '@/components/ui/button';
import {defaultConnections,sourcePorts,connectionPorts,isConnectionMap,type ConnectionMap,type ConnectionTarget} from '@/lib/owner-wiring';

type User={id:string;email:string;name:string;permissions:string[]};
type InlineLink={field:string;value?:string};
type InlineProject={projectId:string;name:string;slug:string;ownerId:string;bindings:Record<string,InlineLink>};
const inlineFields=[['displayName','Profile name'],['cashtag','Cashtag / handle'],['balance','Demo cash balance'],['secondaryValue','Demo savings'],['headline','Page headline'],['accountLabel','Account label']];
export function ConnectionsBoard(){
 const[connections,setConnections]=useState<ConnectionMap>({...defaultConnections}),[loading,setLoading]=useState(true),[error,setError]=useState(''),[saving,setSaving]=useState(false),[canEdit,setCanEdit]=useState(false),[jsonMode,setJsonMode]=useState(false),[raw,setRaw]=useState(''),[users,setUsers]=useState<User[]>([]),[owner,setOwner]=useState(false),[selected,setSelected]=useState<ConnectionTarget>('card.front.cashtag');const[inlineProjects,setInlineProjects]=useState<InlineProject[]>([]),[inlineBusy,setInlineBusy]=useState(false);
 useEffect(()=>{void Promise.all([fetch('/api/studio/connections',{cache:'no-store'}).then(async r=>{const x=await r.json();if(!r.ok)throw Error(x.error||'Permission denied');setConnections(x.connections);setCanEdit(x.canEdit)}),fetch('/api/studio/permissions').then(r=>r.ok?r.json():null).then(x=>{if(x?.users){setUsers(x.users);setOwner(true);void fetch('/api/studio/inline-links',{cache:'no-store'}).then(r=>r.ok?r.json():null).then(result=>{if(result?.projects)setInlineProjects(result.projects)})}})]).catch(e=>setError((e as Error).message)).finally(()=>setLoading(false))},[]);
 const edited=useMemo(()=>Object.keys(connections).some(k=>connections[k as ConnectionTarget]!==defaultConnections[k as ConnectionTarget]),[connections]);
 const selectSource=(target:ConnectionTarget,source:string)=>{const next={...connections,[target]:source};if(isConnectionMap(next))setConnections(next);else toast.error('These ports use different data types')};
 async function save(){setSaving(true);try{if(!isConnectionMap(connections))throw Error('Connect matching types only');const r=await fetch('/api/studio/connections',{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify({connections})});const x=await r.json();if(!r.ok)throw Error(x.error||'Unable to save');toast.success('Connections saved for live Cash App demos')}catch(e){toast.error((e as Error).message)}finally{setSaving(false)}}
 async function reconnectInline(projectId:string,selector:string,field:string){setInlineBusy(true);try{const r=await fetch('/api/studio/inline-links',{method:'PATCH',headers:{'Content-Type':'application/json'},body:JSON.stringify({projectId,selector,field})});const x=await r.json();if(!r.ok)throw Error(x.error||'Unable to reconnect');setInlineProjects(prev=>prev.map(p=>p.projectId===projectId?{...p,bindings:{...p.bindings,[selector]:{field}}}:p));toast.success('Saved: the next live preview will use this linked field')}catch(e){toast.error((e as Error).message)}finally{setInlineBusy(false)}}
 const editor=()=>{setRaw(JSON.stringify(connections,null,2));setJsonMode(x=>!x)};
 const parse=()=>{try{const x=JSON.parse(raw);if(!isConnectionMap(x))throw Error('Every output needs one compatible source.');setConnections(x);setJsonMode(false);toast.success('JSON applied; save to publish')}catch(e){toast.error((e as Error).message)}};
 async function changePermission(userId:string,permission:string,checked:boolean){const person=users.find(u=>u.id===userId);if(!person)return;const permissions=checked?[...person.permissions,permission]:person.permissions.filter(p=>p!==permission);try{const r=await fetch('/api/studio/permissions',{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify({userId,permissions})});const x=await r.json();if(!r.ok)throw Error(x.error||'Not authorized');setUsers(us=>us.map(u=>u.id===userId?{...u,permissions}:u));toast.success('Permissions saved')}catch(e){toast.error((e as Error).message)}}
 return <WorkspaceShell title="Owner Studio · Visual Connections" description="Connect saved LARP data to visible fields. No coding or source-file editing required." actions={<Button variant="outline" asChild><Link href="/developer"><ArrowLeft size={16}/> Owner Studio</Link></Button>}>
 {loading?<div className="glass-panel p-8">Loading connections...</div>:error?<div className="glass-panel p-8 text-red-500">{error}</div>:<div className="space-y-5 max-w-7xl min-w-0 mx-auto">
 <div className="glass-panel p-4 sm:p-5 flex flex-wrap gap-2 justify-between items-center"><div className="flex items-center gap-2"><GitBranch size={20} className="text-primary"/><div><h2 className="font-bold">Cash App connection graph</h2><p className="text-xs text-muted-foreground">Select an output below, then plug it into a compatible saved field.</p></div></div><div className="flex flex-wrap gap-2"><Button variant="outline" size="sm" onClick={editor}><Code2 size={15}/>{jsonMode?'Visual view':'View JSON'}</Button><Button variant="outline" size="sm" disabled={!canEdit} onClick={()=>setConnections({...defaultConnections})}><RotateCcw size={15}/> Reset</Button><Button variant="gradient" size="sm" disabled={!canEdit||saving} onClick={()=>void save()}><Save size={15}/>{saving?'Saving':'Save links'}</Button></div></div>
 {jsonMode?<section className="glass-panel p-5 space-y-3"><p className="text-sm text-muted-foreground">Read or edit connection configuration, not executable JavaScript. The server validates each link before saving.</p><textarea spellCheck={false} className="w-full h-[440px] max-w-full p-4 rounded-lg font-mono text-xs bg-background border border-border" value={raw} onChange={e=>setRaw(e.target.value)} readOnly={!canEdit}/><Button disabled={!canEdit} onClick={parse}>Apply JSON to graph</Button></section>:<>
 <section className="glass-panel p-4 sm:p-6 overflow-x-auto"><div className="min-w-[640px] grid grid-cols-[230px_1fr_230px] gap-3"><div className="space-y-2"><h3 className="font-bold text-sm mb-3">Saved inputs</h3>{sourcePorts.map(s=><div key={s.id} className="rounded-lg bg-slate-800 text-white px-3 py-2.5 text-xs flex justify-between items-center h-11"><span>{s.label}</span><span className="bg-violet-400 w-2.5 h-2.5 rounded-full shrink-0"/></div>)}</div><div className="flex items-center min-h-[590px]"><svg aria-label="Field connections" role="img" viewBox="0 0 250 600" className="w-full h-[600px]" preserveAspectRatio="none">{connectionPorts.map((t,j)=>{const i=sourcePorts.findIndex(s=>s.id===connections[t.id]);return <path key={t.id} d={`M 0 ${i*52+22} C 90 ${i*52+22}, 140 ${j*52+22}, 250 ${j*52+22}`} stroke={selected===t.id?'#a78bfa':'#64748b'} strokeWidth={selected===t.id?3:1.6} opacity={selected===t.id?1:.6} fill="none"/>})}</svg></div><div className="space-y-2"><h3 className="font-bold text-sm mb-3">Visible outputs</h3>{connectionPorts.map(t=><button key={t.id} type="button" onClick={()=>setSelected(t.id)} className={`h-11 w-full rounded-lg border px-3 text-left text-xs flex items-center gap-2 ${selected===t.id?'bg-primary/15 border-primary text-primary':'bg-muted/35 hover:border-primary/40'}`}><span className="h-2.5 w-2.5 shrink-0 rounded-full bg-primary"/>{t.label}</button>)}</div></div></section>
 <section className="glass-panel p-5 grid md:grid-cols-2 gap-5 items-end"><div><label htmlFor="connection-select" className="text-sm font-bold">Edit selected output: {connectionPorts.find(t=>t.id===selected)?.label}</label><p className="text-xs text-muted-foreground mt-1">Connected to the source field below. Changing it affects all LARPs using this Cash App preset.</p></div><div><select id="connection-select" disabled={!canEdit} value={connections[selected]} onChange={e=>selectSource(selected,e.target.value)} className="border border-border rounded-lg bg-background w-full p-3 text-sm">{sourcePorts.filter(s=>s.kind===connectionPorts.find(t=>t.id===selected)?.kind).map(s=><option key={s.id} value={s.id}>{s.label}</option>)}</select></div><p className="text-xs text-muted-foreground md:col-span-2">{edited?'Custom wiring active.':'Using the original working default links.'} Saving reconnects the next loaded phone and desktop previews. Existing saved project values are not deleted.</p></section>
 </>}
 {owner&&<section className="glass-panel p-5 space-y-4"><div className="flex items-center gap-2"><GitBranch size={18}/><h2 className="font-bold">Saved on-screen LARP connections</h2></div><p className="text-xs text-muted-foreground">These links are created when an account owner holds an editable label in their live LARP, chooses a saved field, and saves. As the platform owner, you can reconnect an existing label to another supported field. This never runs external code.</p>{inlineProjects.length===0?<p className="text-sm text-muted-foreground">No on-screen links yet. Create one by opening a saved LARP and holding or double-clicking an editable text label.</p>:<div className="space-y-4 max-h-[420px] overflow-auto">{inlineProjects.map(p=><div key={p.projectId} className="rounded-xl border border-border p-4 space-y-2"><h3 className="font-bold text-sm">{p.name} <span className="text-xs text-muted-foreground font-normal">({p.slug})</span></h3>{Object.entries(p.bindings).map(([selector,binding])=><div key={selector} className="grid md:grid-cols-[minmax(0,1fr)_230px] gap-2 items-center border-t pt-3"><div className="min-w-0"><div className="text-xs font-semibold">{binding.field==='custom'?'Custom local text':binding.field}</div><code title={selector} className="text-[10px] text-muted-foreground break-all">{selector}</code></div><select disabled={inlineBusy} aria-label={'Link selected text for '+p.name} className="w-full rounded-lg border p-2 bg-background text-xs" value={binding.field} onChange={e=>void reconnectInline(p.projectId,selector,e.target.value)}>{binding.field==='custom'&&<option value="custom">Custom local text</option>}{inlineFields.map(([value,label])=><option key={value} value={value}>{label}</option>)}</select></div>)}</div>)}</div>}</section>}
 {owner&&<section className="glass-panel p-5 space-y-4"><div className="flex items-center gap-2"><ShieldCheck size={19}/><h2 className="font-bold">Give staff limited access</h2></div><p className="text-xs text-muted-foreground">Only the configured owner can change staff permissions. These permissions do not grant billing, user management, file uploads, or full Owner Studio access.</p><div className="space-y-3">{users.map(u=><div className="border border-border rounded-xl p-4 grid md:grid-cols-[minmax(160px,1fr)_2fr] gap-3" key={u.id}><div className="min-w-0"><div className="text-sm font-bold truncate">{u.name}</div><div className="text-xs text-muted-foreground break-all">{u.email}</div></div><div className="flex flex-wrap gap-x-5 gap-y-2 text-xs">{[['insights:view','View insights'],['connections:view','View links'],['connections:edit','Edit links']].map(([id,label])=><label className="flex items-center gap-2" key={id}><input type="checkbox" checked={u.permissions.includes(id)} onChange={e=>void changePermission(u.id,id,e.target.checked)}/>{label}</label>)}</div></div>)}</div></section>}
 <p className="text-xs text-muted-foreground">This graph handles predefined data fields, not arbitrary UI elements or executable scripts. For new app presets, the developer must register supported ports. This prevents unsafe code changes on a live website.</p>
 </div>}
 </WorkspaceShell>
}
