'use client';
import {useEffect,useState} from 'react';
import Link from 'next/link';
import {useRouter,useSearchParams} from 'next/navigation';
import {toast} from 'sonner';
import {ArrowLeft,Code2,Monitor,Save,Smartphone,SlidersHorizontal,X} from 'lucide-react';
import type {LarpTemplate} from '@/lib/catalog';
import type {Project,DisplayData} from '@/lib/models';
import {useAccount,api} from '@/components/providers';
import {WorkspaceShell} from '@/components/workspace-shell';
import {AppUiFrame} from '@/components/app-ui-frame';
import {Button} from '@/components/ui/button';
import {Input} from '@/components/ui/input';
import {Textarea} from '@/components/ui/textarea';
import {Label} from '@/components/ui/label';

/** The blueprint fields change the supplied Cash App demo's data, not its source markup. */
export function CashAppBlueprintEditor({template}:{template:LarpTemplate}){
 const router=useRouter(),params=useSearchParams(),id=params.get('project');
 const {user,createFrom,refreshData}=useAccount();
 const [project,setProject]=useState<Project|null>(null);
 const [values,setValues]=useState<DisplayData|null>(null);
 const [device,setDevice]=useState<'phone'|'desktop'>('phone');
 const [showMobileSettings,setShowMobileSettings]=useState(false);
 const [refreshKey,setRefreshKey]=useState(0);
 const [busy,setBusy]=useState(false);
 const [error,setError]=useState('');
 useEffect(()=>{
  if(!user)return;
  if(!id){router.replace('/my-larps?app=cash-app');return;}
  let active=true;
  void api(`/api/projects/${id}`).then(({project:p}:{project:Project})=>{if(active){setProject(p);setValues({...p.data})}}).catch(e=>{if(active)setError((e as Error).message)});
  return()=>{active=false};
 },[id,user,createFrom,router,template.slug]);
 const set=(patch:Partial<DisplayData>)=>setValues(s=>s?{...s,...patch}:s);
 async function save(){if(!project||!values)return;setBusy(true);try{
  const {project:p}=await api(`/api/projects/${project.id}`,{method:'PUT',body:JSON.stringify({data:values})});
  setProject(p);setValues({...p.data});setRefreshKey(x=>x+1);await refreshData();setShowMobileSettings(false);toast.success('Saved — desktop and phone previews updated');
 }catch(e){toast.error((e as Error).message)}finally{setBusy(false)}}
 return <WorkspaceShell title="Cash App Blueprint" description="Edit fictional demo fields. Original desktop and mobile HTML, CSS, and JavaScript stay untouched." actions={<Button asChild variant="outline" size="sm"><Link href="/my-larps"><ArrowLeft size={15}/> My LARPs</Link></Button>}>
  {!user?<div className="glass-panel p-6">Sign in to create and edit a demo.</div>:error?<div className="glass-panel p-6"><p>{error}</p><Link href="/pricing" className="text-primary underline">View access plans</Link></div>:!project||!values?<div className="glass-panel p-6">Loading your Cash App project…</div>:
   <div className="grid xl:grid-cols-[340px_minmax(0,1fr)] gap-5 items-start">
    {showMobileSettings&&<button type="button" className="fixed inset-0 z-[65] bg-black/70 lg:hidden" aria-label="Close settings" onClick={()=>setShowMobileSettings(false)}/>}
    <div className={showMobileSettings?"glass-panel fixed inset-x-0 bottom-0 z-[70] max-h-[80dvh] overflow-y-auto rounded-t-3xl p-5 space-y-5 shadow-2xl lg:static lg:max-h-none lg:overflow-visible lg:rounded-xl":"hidden lg:block glass-panel p-5 space-y-5"}>
     <div className="flex justify-between items-start gap-2"><div><h2 className="font-black text-lg">Edit settings</h2><p className="text-xs text-muted-foreground mt-1">Your edits are saved per project, and applied to both versions of the original interface.</p></div><Button type="button" className="lg:hidden" size="icon" variant="ghost" aria-label="Close editing settings" onClick={()=>setShowMobileSettings(false)}><X size={18}/></Button></div>
     <div className="space-y-2"><h3 className="font-bold text-sm">Profile / identity</h3><Label>Display name</Label><Input value={values.displayName} maxLength={70} onChange={e=>set({displayName:e.target.value})}/><Label>Demo $cashtag</Label><Input value={values.cashtag||'cashtag'} maxLength={30} onChange={e=>set({cashtag:e.target.value.replace(/[^a-zA-Z0-9_]/g,'')})}/></div>
     <div className="border-t border-border pt-4 space-y-2"><h3 className="font-bold text-sm">Cash App accent color</h3><Label>Preset green</Label><Input type="color" className="w-full h-12 p-1" value={/^#[0-9a-fA-F]{6}$/.test(values.accent||'')?values.accent:'#00D632'} onChange={e=>set({accent:e.target.value})}/><p className="text-[11px] text-muted-foreground">Color applies to supported preview elements when you save.</p></div><div className="border-t border-border pt-4 space-y-2"><h3 className="font-bold text-sm">Simulated money</h3><Label>Cash balance ($)</Label><Input type="number" min={0} max={999999999} step="0.01" value={values.balance} onChange={e=>set({balance:Number(e.target.value)})}/><Label>Savings balance ($)</Label><Input type="number" min={0} max={999999999} step="0.01" value={values.secondaryValue} onChange={e=>set({secondaryValue:Number(e.target.value)})}/><p className="text-[11px] text-muted-foreground">Display-only fictional amounts. No transfers or real accounts.</p></div>
     <div className="border-t border-border pt-4 space-y-2"><h3 className="font-bold text-sm flex gap-2 items-center"><Code2 size={16}/> Custom component styling</h3><p className="text-xs text-muted-foreground">Optional scoped CSS overrides for your preview. Leave blank to preserve the original design. External URLs, imports, scripts and fonts are blocked.</p><Textarea className="font-mono text-xs min-h-40" rows={7} maxLength={6000} value={values.customCss||''} onChange={e=>set({customCss:e.target.value})} placeholder="/* e.g. .your-selector { letter-spacing: .02em; } */"/></div>
     <Button variant="gradient" disabled={busy} className="w-full" onClick={()=>void save()}><Save size={16}/>{busy?'Saving…':'Save & refresh previews'}</Button>
    </div>
    <div className="glass-panel p-3 sm:p-5"><div className="flex items-center justify-between flex-wrap gap-3 mb-5"><Button type="button" variant="gradient" className="w-full lg:hidden" onClick={()=>setShowMobileSettings(true)}><SlidersHorizontal size={16}/> Edit settings</Button><div><h2 className="font-black">Original app preview</h2><p className="text-xs text-muted-foreground">Choose the existing desktop or mobile capture</p></div><div className="flex gap-2"><Button size="sm" variant={device==='phone'?'gradient':'outline'} onClick={()=>setDevice('phone')}><Smartphone size={15}/> Phone</Button><Button size="sm" variant={device==='desktop'?'gradient':'outline'} onClick={()=>setDevice('desktop')}><Monitor size={15}/> Desktop</Button></div></div>
     <div className="min-h-[690px] flex justify-center bg-gradient-to-br from-violet-500/10 via-transparent to-sky-500/10 rounded-xl p-4"><AppUiFrame template={template} phone={device==='phone'} ownerPreview projectId={project.id} refreshKey={refreshKey}/></div>
     <p className="text-xs text-muted-foreground mt-4">Click “Pop out” to browse the working version in a new tab. Your original source files stay unchanged; saves affect only this project's simulated values and optional CSS.</p>
    </div>
   </div>}
 </WorkspaceShell>;
}
