'use client';
import React,{useCallback,useEffect,useState} from 'react';
import {Save,RefreshCw} from 'lucide-react';
import {toast} from 'sonner';
import {Button} from '@/components/ui/button';

type Field={key:string;label:string;type:string;value:unknown;options?:Array<{value:string;label:string}>};
type Snapshot={title:string;fields:Field[];supported:boolean};
export function NativeSettingsPanel({projectId,appName}:{projectId:string;appName:string}){
 const [snapshot,setSnapshot]=useState<Snapshot|null>(null);
 const [draft,setDraft]=useState<Record<string,unknown>>({});
 const [busy,setBusy]=useState(false);const[error,setError]=useState('');const[listErrors,setListErrors]=useState<Record<string,string>>({});const[rawLists,setRawLists]=useState<Record<string,string>>({});
 const refresh=useCallback(async()=>{
  try{const response=await fetch(`/api/projects/${encodeURIComponent(projectId)}/native-settings`,{credentials:'same-origin',cache:'no-store'});
   const result=await response.json();if(!response.ok)throw new Error(result.error||'Settings unavailable.');
   setSnapshot(result);setDraft({});setListErrors({});setRawLists({});setError('');
  }catch(e){setSnapshot(null);setError((e as Error).message)}
 },[projectId]);
 useEffect(()=>{void refresh()},[refresh]);
 // When the original in-app hold-to-edit Save succeeds, refresh the sidebar
 // from the same account-owned settings record instead of displaying stale fields.
 useEffect(()=>{
  const sync=(event:Event)=>{const detail=(event as CustomEvent<{projectId?:string}>).detail;if(detail?.projectId===projectId)void refresh()};
  window.addEventListener('larpdevice:project-updated',sync);
  window.addEventListener('larpdevice:settings-saved',sync);
  let channel:BroadcastChannel|undefined;
  try{channel=new BroadcastChannel('larpdevice-project-sync');channel.onmessage=e=>sync(new CustomEvent('larpdevice:project-updated',{detail:e.data}))}catch{}
  return()=>{window.removeEventListener('larpdevice:project-updated',sync);window.removeEventListener('larpdevice:settings-saved',sync);channel?.close()};
 },[projectId,refresh]);
 const change=(k:string,value:unknown)=>setDraft(p=>({...p,[k]:value}));
 const readValue=(f:Field)=>Object.hasOwn(draft,f.key)?draft[f.key]:f.value;
 async function save(){if(!Object.keys(draft).length||Object.keys(listErrors).length)return;setBusy(true);try{
  const response=await fetch(`/api/projects/${encodeURIComponent(projectId)}/native-settings`,{method:'PATCH',credentials:'same-origin',headers:{'Content-Type':'application/json'},body:JSON.stringify(draft)});
  const result=await response.json().catch(()=>({}));if(!response.ok)throw new Error(result.error||'Save failed.');
  toast.success('Saved to this LARP. The app preview will refresh.');
  window.dispatchEvent(new CustomEvent('larpdevice:settings-saved',{detail:{projectId}}));
  const channel=new BroadcastChannel('larpdevice-project-sync');channel.postMessage({projectId});channel.close();
  await refresh();
 }catch(e){toast.error((e as Error).message)}finally{setBusy(false)}}
 async function choosePicture(file:File|null,field:Field){if(!file)return;
  if(!['image/png','image/jpeg','image/webp'].includes(file.type)){toast.error('Use a PNG, JPEG or WebP image.');return}
  if(file.size>8_000_000){toast.error('Choose an image under 8 MB.');return}
  const image=new Image(),url=URL.createObjectURL(file);
  image.onload=()=>{const canvas=document.createElement('canvas');canvas.width=256;canvas.height=256;
   const ctx=canvas.getContext('2d');if(!ctx){URL.revokeObjectURL(url);return}
   const crop=Math.min(image.naturalWidth,image.naturalHeight);
   ctx.drawImage(image,(image.naturalWidth-crop)/2,(image.naturalHeight-crop)/2,crop,crop,0,0,256,256);
   const data=canvas.toDataURL('image/jpeg',0.8);URL.revokeObjectURL(url);
   if(data.length>260000){toast.error('The resized picture is too large.');return}change(field.key,data);
  };image.onerror=()=>{URL.revokeObjectURL(url);toast.error('Could not open this picture.')};image.src=url;
 }
 return <section className="space-y-4">
  <div className="flex items-center justify-between gap-2"><div><h4 className="text-sm font-bold">{snapshot?.title||`${appName} settings`}</h4><p className="text-xs text-muted-foreground">These are the original built-in app settings, saved to your own simulated LARP.</p></div><Button variant="outline" size="sm" onClick={()=>void refresh()}><RefreshCw size={15}/> Reload</Button></div>
  {error&&<p className="rounded-lg bg-amber-500/10 border border-amber-400/30 p-3 text-xs">{error}</p>}
  {snapshot?.fields.map(f=>{const value=readValue(f);const type=f.type;return <div key={f.key} className="space-y-1.5 rounded-xl border border-border/70 p-3">
    <label htmlFor={`native-${f.key}`} className="text-xs font-semibold">{f.label}</label>
    {type==='toggle'?<label className="flex items-center gap-3 text-sm"><input id={`native-${f.key}`} type="checkbox" checked={Boolean(value)} onChange={e=>change(f.key,e.target.checked)}/> Enabled</label>
    :type==='image'?<div className="space-y-2"><input id={`native-${f.key}`} type="file" accept="image/png,image/jpeg,image/webp" className="text-xs w-full" onChange={e=>void choosePicture(e.target.files?.[0]||null,f)}/>{typeof value==='string'&&value.startsWith('data:image/')&&<img src={value} alt="Selected profile image" className="h-16 w-16 rounded-xl object-cover"/>}<button className="text-xs underline" type="button" onClick={()=>change(f.key,'')}>Remove image</button></div>
    :type==='select'&&f.options?.length?<select id={`native-${f.key}`} className="w-full rounded-lg border bg-background p-2.5 text-sm" value={String(value??'')} onChange={e=>change(f.key,e.target.value)}>{f.options.map((option,i)=><option value={option.value} key={i}>{option.label}</option>)}</select>
    :type==='list'?<textarea id={`native-${f.key}`} rows={4} className="w-full rounded-lg border bg-background p-2.5 font-mono text-xs" value={Object.hasOwn(rawLists,f.key)?rawLists[f.key]:(typeof value==='string'?value:JSON.stringify(value??[],null,2))} onChange={e=>{const raw=e.target.value;setRawLists(old=>({...old,[f.key]:raw}));try{const parsed=JSON.parse(raw);if(!Array.isArray(parsed))throw new Error('Use a JSON array');change(f.key,parsed);setListErrors(old=>{const next={...old};delete next[f.key];return next})}catch{setListErrors(old=>({...old,[f.key]:'Use valid JSON containing an array.'}))}}} aria-label={`${f.label} JSON array`}/>
    :<input id={`native-${f.key}`} className="w-full rounded-lg border bg-background p-2.5 text-sm" type={['number','money'].includes(type)?'number':'text'} step={type==='money'?'0.01':type==='number'?'any':undefined} value={String(value??'')} onChange={e=>change(f.key,['number','money'].includes(type)?Number(e.target.value):e.target.value)}/>}
   </div>})}
  {Object.keys(listErrors).length>0&&<p role="alert" className="text-xs text-amber-500">Check the list formatting before saving.</p>}
  <Button type="button" className="w-full" disabled={!Object.keys(draft).length||busy||Object.keys(listErrors).length>0} onClick={()=>void save()}><Save size={16}/>{busy?'Saving…':`Save ${Object.keys(draft).length||''} setting${Object.keys(draft).length===1?'':'s'}`}</Button>
  <p className="text-xs text-muted-foreground">The app’s built-in hold-to-edit sheet uses this same saved settings record. Captured features that require the original external server may still be unavailable.</p>
 </section>
}
