'use client';
import {useEffect,useMemo,useState} from 'react';
import Link from 'next/link';
import {Images,Monitor,Smartphone,Search,ArrowUpRight,FolderOpen,Upload,Save} from 'lucide-react';
import {toast} from 'sonner';
import {WorkspaceShell} from '@/components/workspace-shell';
import {BrandIcon} from '@/components/brand-icon';
import type {LarpTemplate} from '@/lib/catalog';
import {Button} from '@/components/ui/button';
import {Input} from '@/components/ui/input';
import {StatusBadge} from '@/components/common';
export interface CapturedAssetInfo{name:string;devices:{phone:boolean;desktop:boolean};media:{phone:string[];desktop:string[]};sourceFolders:string[]}
type Entry={template:LarpTemplate;capture:CapturedAssetInfo};
const url=(slug:string,device:string,asset:string)=>'/api/app-gallery/'+encodeURIComponent(slug)+'/'+device+'/'+asset.split('/').map(encodeURIComponent).join('/');
export function AppAssetBrowser({assets}:{assets:Entry[]}){
 const [catalog,setCatalog]=useState(assets),[search,setSearch]=useState(''),[selected,setSelected]=useState('cash-app'),[device,setDevice]=useState<'phone'|'desktop'>('phone'),[count,setCount]=useState(48);
 const [draft,setDraft]=useState<{name:string;category:string;icon:string;thumbnail:string;publicVisible:boolean}>({name:'',category:'',icon:'',thumbnail:'',publicVisible:true}),[saving,setSaving]=useState(false);
 useEffect(()=>{const slug=new URLSearchParams(window.location.search).get('app');if(slug&&catalog.some(a=>a.template.slug===slug))setSelected(slug)},[catalog]);
 const filtered=useMemo(()=>catalog.filter(a=>a.template.name.toLowerCase().includes(search.toLowerCase())),[catalog,search]);
 const item=catalog.find(a=>a.template.slug===selected)||filtered[0];
 const photos=item?.capture.media?.[device]||[];
 const total=catalog.filter(x=>x.template.uiReady).length;
 useEffect(()=>{if(item)setDraft({name:item.template.name,category:item.template.category,icon:item.template.icon,thumbnail:item.template.thumbnail||'',publicVisible:item.template.publicVisible===true})},[item?.template.slug]);
 async function upload(file:File|undefined,kind:'icon'|'thumbnail'){if(!file||!item)return;try{setSaving(true);const form=new FormData();form.set('file',file);form.set('purpose',kind);const response=await fetch('/api/studio/assets',{method:'POST',body:form});const value=await response.json();if(!response.ok)throw Error(value.error||'Upload failed');setDraft(v=>({...v,[kind]:value.url}));toast.success(kind==='icon'?'Icon uploaded. Save to publish.':'Thumbnail uploaded. Save to publish.')}catch(e){toast.error((e as Error).message)}finally{setSaving(false)}}
 async function save(){if(!item)return;setSaving(true);try{const response=await fetch('/api/studio/catalog/'+encodeURIComponent(item.template.slug),{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify(draft)});const value=await response.json();if(!response.ok)throw Error(value.error||'Could not save changes');setCatalog(a=>a.map(x=>x.template.slug===item.template.slug?{...x,template:value.template}:x));toast.success('App icon, thumbnail and listing updated for Our LARPs')}catch(e){toast.error((e as Error).message)}finally{setSaving(false)}}
 return <WorkspaceShell title="App UIs, Photos & Icons" description={`${total} available local app previews. Every imported image is grouped with its app; missing previews appear as Coming Soon.`} actions={<Button asChild variant="outline" size="sm"><Link href="/library">Browse Our LARPs</Link></Button>}>
 <div className="grid lg:grid-cols-[285px_minmax(0,1fr)] gap-5 items-start">
  <aside className="glass-panel p-3 lg:sticky lg:top-20"><div className="flex items-center gap-2 font-semibold px-2 py-2"><FolderOpen size={16}/> Local app directory</div><div className="relative mb-3"><Search className="absolute left-2 top-3 text-muted-foreground" size={15}/><Input className="pl-8" placeholder="Find an app..." value={search} onChange={e=>setSearch(e.target.value)}/></div><div className="max-h-[65vh] overflow-y-auto space-y-1">{filtered.map(a=><button key={a.template.slug} onClick={()=>{setSelected(a.template.slug);setDevice(a.capture.devices.phone?'phone':'desktop');setCount(48)}} className={'flex items-center text-left gap-2 w-full px-2 py-2 rounded-xl '+(a.template.slug===item?.template.slug?'bg-primary/15':'hover:bg-muted/60')}><BrandIcon template={a.template} size={30}/><span className="flex-1 min-w-0"><span className="block text-xs font-semibold truncate">{a.template.name}</span><span className="text-[10px] text-muted-foreground">{a.template.uiReady?'Available':'Coming Soon'}</span></span></button>)}</div></aside>
  <section className="glass-panel p-4 md:p-6 min-w-0">{item?<><div className="flex flex-wrap gap-3 items-center justify-between"><div className="flex items-center gap-3"><BrandIcon template={item.template} size={54}/><div><h2 className="text-xl font-bold">{item.template.name}</h2><StatusBadge status={item.template.status}/></div></div><Button variant="outline" size="sm" asChild><Link href={`/larp/${item.template.slug}`} target="_blank">Open app page <ArrowUpRight size={14}/></Link></Button></div>
  <div className="flex flex-wrap gap-2 items-center my-5"><Button size="sm" variant={device==='phone'?'gradient':'outline'} onClick={()=>{setDevice('phone');setCount(48)}}><Smartphone size={14}/> Phone {item.capture.devices.phone?'✓':''}</Button><Button size="sm" variant={device==='desktop'?'gradient':'outline'} onClick={()=>{setDevice('desktop');setCount(48)}}><Monitor size={14}/> Desktop {item.capture.devices.desktop?'✓':''}</Button></div>
  {item.template.uiReady&&<div className="border border-border rounded-xl p-4 bg-muted/20 mb-6"><div className="font-bold text-sm mb-1">Original {device} preview</div>
 <div className="mt-3 mb-4 rounded-xl overflow-hidden w-[180px] max-w-full border border-border bg-black"><img className="w-full h-auto object-contain" alt={`${item.template.name} original UI screenshot`} src={`/app-thumbnails/${item.template.slug}.webp`}/></div><p className="text-xs text-muted-foreground mb-3">Uses the bundled local interface. Missing device captures fall back to the other available device.</p><Button size="sm" asChild><Link href={`/preview/${item.template.slug}?device=${device}`} target="_blank" rel="noopener noreferrer">Open full-tab UI <ArrowUpRight size={15}/></Link></Button></div>}
  <section className="rounded-xl border border-primary/25 bg-primary/5 p-4 mb-6" aria-label="App icon and thumbnail manager"><div className="flex flex-wrap gap-3 items-center justify-between"><h3 className="font-bold text-lg">App UI, icon & Our LARPs thumbnail</h3><Button size="sm" variant="gradient" disabled={saving} onClick={()=>void save()}><Save size={15}/>{saving?'Saving…':'Save listing'}</Button></div><p className="text-xs text-muted-foreground my-3">All assets for this app are managed here. New thumbnails appear on the Our LARPs page and homepage cards without changing the original embedded app UI.</p><div className="grid sm:grid-cols-2 gap-4"><label className="text-xs font-semibold">App name<Input className="mt-1" value={draft.name} onChange={e=>setDraft(v=>({...v,name:e.target.value}))}/></label><label className="text-xs font-semibold">Category<Input className="mt-1" value={draft.category} onChange={e=>setDraft(v=>({...v,category:e.target.value}))}/></label><label className="text-xs font-semibold">App icon (PNG, JPEG, WebP up to 1 MB)<div className="flex items-center gap-3 mt-2">{draft.icon&&<img src={draft.icon} alt="Selected app icon" className="w-12 h-12 rounded-xl object-contain"/>}<Input type="file" accept="image/png,image/jpeg,image/webp" aria-label="Upload app icon" onChange={e=>void upload(e.target.files?.[0],'icon')}/></div></label><label className="text-xs font-semibold">Our LARPs card thumbnail (up to 5 MB)<div className="flex items-center gap-3 mt-2"><img src={draft.thumbnail||`/app-thumbnails/${item.template.slug}.webp`} alt="Current Our LARPs thumbnail" className="w-24 h-16 rounded-lg border object-cover object-top"/><Input type="file" accept="image/png,image/jpeg,image/webp" aria-label="Upload card thumbnail" onChange={e=>void upload(e.target.files?.[0],'thumbnail')}/></div></label><label className="text-xs font-semibold flex gap-2 items-center"><input type="checkbox" checked={draft.publicVisible} onChange={e=>setDraft(v=>({...v,publicVisible:e.target.checked}))}/> Show this app in Our LARPs and the sidebar when a working UI is available</label></div>{draft.thumbnail&&<button className="text-xs text-primary mt-3 underline" onClick={()=>setDraft(v=>({...v,thumbnail:''}))}>Restore automatically captured thumbnail</button>}</section>
  <div className="flex gap-2 items-center justify-between mb-3"><h3 className="text-lg font-bold flex gap-2 items-center"><Images size={18}/> Imported photos & assets</h3><span className="text-xs text-muted-foreground">{photos.length} files</span></div>
  {photos.length?<div className="grid grid-cols-2 sm:grid-cols-3 xl:grid-cols-4 gap-3">{photos.slice(0,count).map((file,i)=><a key={file+'-'+i} target="_blank" rel="noopener noreferrer" href={url(item.template.slug,device,file)} className="border rounded-xl overflow-hidden hover:border-primary/60 bg-background group"><div className="h-36 bg-muted/40 flex items-center justify-center"><img src={url(item.template.slug,device,file)} loading="lazy" alt={`${item.template.name} captured UI asset ${i+1}`} className="max-h-full max-w-full object-contain"/></div><div className="p-2 text-[10px] truncate text-muted-foreground" title={file}>{file.split('/').pop()}</div></a>)}</div>:<div className="border border-dashed border-border rounded-2xl py-12 text-sm text-muted-foreground text-center">No images were captured for this device.</div>}
  {photos.length>count&&<Button variant="outline" className="mt-5 w-full" onClick={()=>setCount(n=>n+48)}>Show more photos ({photos.length-count} remaining)</Button>}
  {!item.template.uiReady&&<div className="mt-4 rounded-xl border border-amber-500/30 p-3 text-xs text-amber-500">Coming Soon — the source archive does not contain a usable browser preview for this app. Images alone do not count as an available app.</div>}
  </>:<p className="text-muted-foreground p-8">No matching apps.</p>}</section>
 </div>
 </WorkspaceShell>
}
