'use client';
import{useEffect,useMemo,useState}from'react';
import{toast}from'sonner';
import Link from'next/link';
import{ArrowLeft,Upload,Image as ImageIcon,Film,Trash2,X,Play,Filter}from'lucide-react';
import{WorkspaceShell}from'@/components/workspace-shell';
import{Button}from'@/components/ui/button';
import{Input}from'@/components/ui/input';
import{mediaCategories}from'@/lib/media-types';
import type{MediaItem}from'@/lib/platform-store';

const qualityOptions=['SD','HD','Full HD','4K','Other'];
const videoOptions=['standard','loop','b-roll','other'];
export function MediaLibrary({owner=false}:{owner?:boolean}){
 const [items,setItems]=useState<MediaItem[]>([]),[previewOnly,setPreviewOnly]=useState(false),[loading,setLoading]=useState(true),[busy,setBusy]=useState(false),[chosen,setChosen]=useState<MediaItem|null>(null);
 const [category,setCategory]=useState('all'),[type,setType]=useState('all'),[videoType,setVideoType]=useState('all'),[quality,setQuality]=useState('all'),[resolution,setResolution]=useState('all'),[orientation,setOrientation]=useState('all'),[sort,setSort]=useState('newest');
 const [file,setFile]=useState<File|null>(null),[name,setName]=useState(''),[uploadCat,setUploadCat]=useState<string>('Lifestyle'),[uploadQuality,setUploadQuality]=useState('Full HD'),[uploadVideoType,setUploadVideoType]=useState('standard'),[width,setWidth]=useState(''),[height,setHeight]=useState('');
 async function reload(){setLoading(true);try{const r=await fetch('/api/media',{cache:'no-store'});if(r.status===402&&!owner){const p=await fetch('/api/media?preview=1',{cache:'no-store'});const d=await p.json();setItems(d.items||[]);setPreviewOnly(true);return;}const d=await r.json();if(!r.ok)throw Error(d.error);setItems(d.items||[]);setPreviewOnly(false)}catch(e){toast.error((e as Error).message)}finally{setLoading(false)}}
 useEffect(()=>{void reload()},[]);
 useEffect(()=>{if(!file){setWidth('');setHeight('');return;}let disposed=false;
  if(file.type.startsWith('image/')){void createImageBitmap(file).then(bitmap=>{if(!disposed){setWidth(String(bitmap.width));setHeight(String(bitmap.height));}bitmap.close()}).catch(()=>{});}
  else if(file.type.startsWith('video/')){const url=URL.createObjectURL(file);const video=document.createElement('video');video.preload='metadata';video.onloadedmetadata=()=>{if(!disposed){setWidth(String(video.videoWidth));setHeight(String(video.videoHeight))}URL.revokeObjectURL(url)};video.onerror=()=>URL.revokeObjectURL(url);video.src=url;return()=>{disposed=true;URL.revokeObjectURL(url)}}
  return()=>{disposed=true};
 },[file]);

 const filtered=useMemo(()=>{const result=items.filter(m=>(category==='all'||m.category===category)&&(type==='all'||m.type===type)&&(videoType==='all'||m.videoType===videoType)&&(quality==='all'||m.quality===quality)&&(orientation==='all'||m.orientation===orientation)&&(resolution==='all'||(m.width&&m.height?`${m.width}x${m.height}`:'Unknown')===resolution));if(sort==='popular')result.sort((a,b)=>b.views-a.views);else if(sort==='newest')result.sort((a,b)=>b.createdAt.localeCompare(a.createdAt));else result.sort(()=>Math.random()-.5);return result},[items,category,type,videoType,quality,resolution,orientation,sort]);
 const resolutions=Array.from(new Set(items.map(m=>m.width&&m.height?`${m.width}x${m.height}`:'Unknown')));
 function choose(m:MediaItem){if(previewOnly)return;setChosen(m);void fetch('/api/media/'+encodeURIComponent(m.id),{method:'POST'}).then(()=>setItems(v=>v.map(x=>x.id===m.id?{...x,views:x.views+1}:x))).catch(()=>{})}
 async function upload(){if(!file)return;setBusy(true);try{const form=new FormData();form.set('file',file);form.set('name',name||file.name);form.set('category',uploadCat);form.set('quality','auto');form.set('videoType',uploadVideoType);form.set('width',width||'0');form.set('height',height||'0');const small=await lowResPreview(file);if(small&&small.size<=40000)form.set('preview',small,'preview.jpg');const r=await fetch('/api/media',{method:'POST',body:form});const d=await r.json();if(!r.ok)throw Error(d.error||'Upload failed');setItems(v=>[d.item,...v]);setFile(null);setName('');setWidth('');setHeight('');toast.success('Media available in the client library')}catch(e){toast.error((e as Error).message)}finally{setBusy(false)}}
 async function remove(id:string){if(!window.confirm('Delete this media file from every user library?'))return;try{const r=await fetch('/api/media/'+id,{method:'DELETE'});const d=await r.json();if(!r.ok||!d.ok)throw Error(d.error||'Unable to delete');setItems(v=>v.filter(x=>x.id!==id));setChosen(null);toast.success('Media deleted')}catch(e){toast.error((e as Error).message)}}
 const mediaUrl=(id:string)=>'/api/media/'+encodeURIComponent(id);
 async function lowResPreview(source:File):Promise<Blob|null>{if(!source.type.startsWith('image/'))return null;try{const bitmap=await createImageBitmap(source);const canvas=document.createElement('canvas');canvas.width=160;canvas.height=100;const ctx=canvas.getContext('2d');if(!ctx){bitmap.close();return null;}ctx.fillStyle='#11111c';ctx.fillRect(0,0,160,100);const scale=Math.min(160/bitmap.width,100/bitmap.height);const w=bitmap.width*scale,h=bitmap.height*scale;ctx.drawImage(bitmap,(160-w)/2,(100-h)/2,w,h);bitmap.close();return await new Promise(resolve=>canvas.toBlob(resolve,'image/jpeg',.48))}catch{return null}}
 return <WorkspaceShell title={owner?'Owner Studio · Media Manager':'Media Library'} description={owner?'Upload, categorize, preview, and delete shared images and videos.':'Browse owner-provided media for creative LARPs.'} actions={owner?<Button asChild variant="outline"><Link href="/developer"><ArrowLeft size={15}/> Owner Studio</Link></Button>:undefined}>
 {previewOnly&&!owner&&<section className="relative overflow-hidden rounded-2xl border border-primary/35 bg-gradient-to-r from-violet-700/15 to-slate-800/15 p-6 mb-6"><div className="text-xs uppercase tracking-widest text-primary font-extrabold">Library preview</div><h2 className="text-2xl font-extrabold mt-2">Unlock the complete Media Library</h2><p className="text-sm text-muted-foreground mt-2 max-w-2xl">Browse low-resolution previews below. A purchased plan or owner-assigned paid plan is required to open, download, or use the full images and videos.</p><Button variant="gradient" asChild className="mt-4"><Link href="/pricing">Upgrade Now</Link></Button></section>}{owner&&<section className="glass-panel p-6 mb-6 space-y-4"><h2 className="font-bold flex gap-2 items-center"><Upload size={18}/> Upload media</h2><p className="text-xs text-muted-foreground">Choose a file, name, and category. Supported image/video dimensions are read automatically; thumbnails fit their preview. PNG, JPG, WebP, MP4, WebM up to 25 MB.</p><div className="grid md:grid-cols-3 gap-3"><div className="md:col-span-2"><label className="block text-xs mb-1">Image or video file</label><Input type="file" accept="image/png,image/jpeg,image/webp,video/mp4,video/webm" onChange={e=>{const f=e.target.files?.[0]||null;setFile(f);setName(f?.name||'');setWidth('');setHeight('')}}/></div><div><label className="block text-xs mb-1">Display name</label><Input value={name} onChange={e=>setName(e.target.value)}/></div><div><label className="block text-xs mb-1">Category</label><select className="w-full h-10 border border-border bg-background rounded-lg px-3" value={uploadCat} onChange={e=>setUploadCat(e.target.value)}>{mediaCategories.map(c=><option key={c}>{c}</option>)}</select></div><div className="md:col-span-2 text-sm text-muted-foreground flex flex-wrap gap-3 items-center"><span>Detected resolution: {width&&height?`${width} × ${height}`:'Not available yet'}</span><span>· Quality set automatically</span></div><details className="md:col-span-3 rounded-lg border p-3"><summary className="text-xs cursor-pointer font-semibold">Advanced metadata (optional)</summary><div className="grid sm:grid-cols-3 gap-3 mt-3"><label className="text-xs">Video type<select className="w-full h-10 border rounded-lg bg-background" value={uploadVideoType} onChange={e=>setUploadVideoType(e.target.value)}>{videoOptions.map(c=><option key={c}>{c}</option>)}</select></label><label className="text-xs">Width override<Input type="number" min="0" max="16000" value={width} onChange={e=>setWidth(e.target.value)}/></label><label className="text-xs">Height override<Input type="number" min="0" max="16000" value={height} onChange={e=>setHeight(e.target.value)}/></label></div></details><div className="flex items-end"><Button variant="gradient" disabled={!file||busy} onClick={()=>void upload()}><Upload size={15}/>{busy?'Uploading…':'Upload to library'}</Button></div></div></section>}
 <div className="glass-panel p-4 mb-5"><div className="flex items-center gap-2 mb-4 font-bold text-sm"><Filter size={16}/> Filters & sorting</div><div className="grid grid-cols-2 md:grid-cols-4 xl:grid-cols-7 gap-2">{[
 ['Category',category,setCategory,['all',...mediaCategories]],['Media type',type,setType,['all','image','video']],['Video type',videoType,setVideoType,['all',...videoOptions]],['Quality',quality,setQuality,['all',...qualityOptions]],['Resolution',resolution,setResolution,['all',...resolutions]],['Orientation',orientation,setOrientation,['all','portrait','landscape','square','unknown']],['Sort',sort,setSort,[ 'newest','popular','random']]
 ].map(([label,value,setter,options])=><label key={label as string} className="text-xs text-muted-foreground">{label as string}<select className="mt-1 w-full h-9 border border-border bg-background text-foreground rounded-lg px-2 text-xs" value={value as string} onChange={e=>(setter as (v:string)=>void)(e.target.value)}>{(options as readonly string[]).map(o=><option value={o} key={o}>{o==='all'?'All':o==='popular'?'Most Popular':o==='newest'?'Newest':o==='random'?'Random':o}</option>)}</select></label>)}</div></div>
 <p className="text-xs text-muted-foreground mb-3">{loading?'Loading media…':`${filtered.length} of ${items.length} files`}</p><div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-5 gap-3">{filtered.map(m=><article key={m.id} className="group overflow-hidden rounded-xl border border-border bg-card"><button type="button" onClick={()=>choose(m)} disabled={previewOnly} className="block w-full relative aspect-video bg-muted overflow-hidden" aria-label={'Preview '+m.name}>{m.type==='image'?<img src={previewOnly?`${mediaUrl(m.id)}/preview`:mediaUrl(m.id)} alt={m.name} loading="lazy" className="w-full h-full object-cover" onError={e=>{(e.currentTarget as HTMLImageElement).style.opacity='0'}}/>:<div className="h-full w-full flex items-center justify-center bg-gradient-to-br from-slate-800 to-violet-950"><Play size={32} className="text-white"/></div>}{previewOnly&&<span className="absolute inset-0 flex justify-center items-center text-xs bg-black/20 text-white font-bold">Preview only · Locked</span>}<span className="absolute bottom-2 left-2 text-[10px] bg-black/70 text-white rounded px-2 py-1">{m.type==='image'?'IMAGE':'VIDEO'}</span></button><div className="p-3"><div className="text-sm font-bold truncate">{m.name}</div><div className="mt-1 text-[11px] text-muted-foreground">{m.category} · {m.quality} · {m.width?`${m.width}×${m.height}`:'Unknown size'}</div><div className="flex justify-between mt-3">{previewOnly?<Link className="text-xs text-primary font-bold" href="/pricing">Upgrade to unlock</Link>:<button className="text-xs text-primary font-bold" onClick={()=>choose(m)}>Preview</button>}{owner&&<button className="text-xs text-red-500" onClick={()=>void remove(m.id)} aria-label={'Delete '+m.name}><Trash2 size={15}/></button>}</div></div></article>)}</div>
 {!loading&&!filtered.length&&<p className="glass-panel p-12 text-center text-sm text-muted-foreground mt-3">No media matches your filters. {owner?'Upload your first file above.':'Check again when the owner adds files.'}</p>}
 {chosen&&<div role="dialog" aria-modal="true" aria-label={chosen.name} className="fixed inset-0 z-[100] bg-black/90 flex flex-col items-center justify-center p-4" onClick={()=>setChosen(null)}><div className="flex justify-between items-center text-white w-full max-w-5xl mb-3"><span className="text-sm font-bold">{chosen.name} · {chosen.category}</span><button aria-label="Close preview" onClick={()=>setChosen(null)}><X/></button></div><div className="max-w-5xl max-h-[80vh] w-full flex justify-center" onClick={e=>e.stopPropagation()}>{chosen.type==='image'?<img src={mediaUrl(chosen.id)} alt={chosen.name} className="max-w-full max-h-[80vh] object-contain"/>:<video src={mediaUrl(chosen.id)} controls autoPlay className="max-w-full max-h-[80vh]"/>}</div></div>}
 </WorkspaceShell>;
}
