"use client";
import { useEffect, useMemo, useState } from "react";
import { API } from "../lib/config";

type Slot = { day: string; time: string; atelier: string; booked: number; capacity: number; available: number; status: "available"|"full" };
type Availability = { term: string; capacity: number; slots: Slot[]; sessions: Record<string, number>; hourly_rate: number; workbook_fee: number };
const atelierDays = [
 ["monday","Speak with Confidence. Build Your Career."],
 ["tuesday","Explore the World. Learn English Along the Way."],
 ["wednesday","Every Story Deserves a Voice. Find Yours in English."],
 ["thursday","Your Favourite Movies. Your Music. Your English."]
] as const;
const times = ["13:00-15:00","15:15-17:15","17:30-19:30"];
const goals = ["Speaking confidently","Professional communication","Grammar and vocabulary","Pronunciation","Travel and culture","Reading","Creative writing","Listening comprehension","Entertainment and popular culture"];
const initial: Availability = {term:"2026-27-term-1",capacity:12,slots:[],sessions:{monday:10,tuesday:10,wednesday:10,thursday:9},hourly_rate:9.6,workbook_fee:13.99};

export default function Registration(){
 const [data,setData]=useState<Availability>(initial);
 const [loading,setLoading]=useState(true);
 const [error,setError]=useState("");
 const [selected,setSelected]=useState<string[]>([]);
 const [preferred,setPreferred]=useState<Record<string,string>>({});
 const [alternates,setAlternates]=useState<Record<string,string[]>>({});
 const [form,setForm]=useState({first_name:"",last_name:"",email:"",phone:"",country:"",date_of_birth:"",proficiency:"",goals:[] as string[],learning_goals:"",accept_terms:false});
 const [submitting,setSubmitting]=useState(false);
 const [result,setResult]=useState<{message:string;invoice_url?:string;student_id?:string}|null>(null);
 const [term,setTerm]=useState("2026-27-term-1");
 const wpConfigured = !API.includes("cms.example.com");

 async function loadAvailability(termId=term){
   setLoading(true); setError("");
   if(!wpConfigured){setData({...initial,term:termId,slots:atelierDays.flatMap(([day,name])=>times.map(time=>({day,time,atelier:name,booked:0,capacity:12,available:12,status:"available" as const})))});setLoading(false);return;}
   try {
    const res=await fetch(`${API}/availability?term=${encodeURIComponent(termId)}`,{cache:"no-store"});
    if(!res.ok) throw new Error("Could not load class availability.");
    const json=await res.json(); setData(json);
   } catch(e){setError(e instanceof Error?e.message:"Availability is temporarily unavailable.");}
   finally{setLoading(false);}
 }
 useEffect(()=>{loadAvailability(term);},[term]);
 const total = useMemo(()=>{
   const hours=selected.reduce((sum,day)=>sum+2*(data.sessions?.[day] ?? 0),0);
   return {hours,tuition:hours*(data.hourly_rate||9.6),total:hours*(data.hourly_rate||9.6)+(selected.length?data.workbook_fee||13.99:0)};
 },[selected,data]);
 const slotsFor=(day:string)=>data.slots.filter(s=>s.day===day);
 function toggleAtelier(day:string){
  setSelected(old=>old.includes(day)?old.filter(x=>x!==day):[...old,day]);
  setPreferred(old=>{const n={...old};delete n[day];return n;});
  setAlternates(old=>{const n={...old};delete n[day];return n;});
 }
 function choosePreferred(day:string,time:string){setPreferred(old=>({...old,[day]:time}));}
 function toggleAlternate(day:string,time:string){
  setAlternates(old=>({...old,[day]:(old[day]||[]).includes(time)?(old[day]||[]).filter(x=>x!==time):[...(old[day]||[]),time].slice(0,2)}));
 }
 function update<K extends keyof typeof form>(key:K,value:(typeof form)[K]){setForm(old=>({...old,[key]:value}));}
 async function submit(e:React.FormEvent){
  e.preventDefault();setResult(null);setError("");
  if(!selected.length){setError("Please select at least one atelier.");return;}
  if(selected.some(day=>!preferred[day])){setError("Choose a preferred available time for each selected atelier.");return;}
  if(!form.accept_terms){setError("Please accept the Academy's terms before continuing.");return;}
  setSubmitting(true);
  try{
   const payload={...form,term,selected_ateliers:selected.map(day=>({day,preferred_time:preferred[day],alternative_times:alternates[day]||[]}))};
   if(!wpConfigured){setResult({message:"Preview mode: connect the WordPress backend to submit a real registration and receive an invoice."});return;}
   const res=await fetch(`${API}/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(payload)});
   const json=await res.json();
   if(!res.ok)throw new Error(json.message||"Registration could not be submitted.");
   setResult({message:json.message||"Registration received. Your invoice has been emailed.",invoice_url:json.invoice_url,student_id:json.student_id});
   setSelected([]);setPreferred({});setAlternates({});
   await loadAvailability(term);
  }catch(e){setError(e instanceof Error?e.message:"Registration failed.");}
  finally{setSubmitting(false);}
 }
 return <div className="registration-shell">
  <div className="registration-main">
   <div className="registration-top"><div><span className="eyebrow">ONLINE ENROLMENT</span><h3>Build your learning plan.</h3></div><label className="term-select">Academic term<select value={term} onChange={e=>setTerm(e.target.value)}><option value="2026-27-term-1">Term 1 · Nov 2026–Jan 2027</option><option value="2026-27-term-2">Term 2 · Feb–Apr 2027</option><option value="2026-27-term-3">Term 3 · May–Jul 2027</option></select></label></div>
   <form onSubmit={submit}>
    <div className="form-block"><div className="form-title"><span>01</span><div><h4>Choose your atelier(s)</h4><p>Select one or more learning experiences.</p></div></div>
     <div className="choice-grid">{atelierDays.map(([day,name],i)=><label className={`choice-card ${selected.includes(day)?"chosen":""}`} key={day}><input type="checkbox" checked={selected.includes(day)} onChange={()=>toggleAtelier(day)}/><span className="choice-num">0{i+1}</span><b>{name}</b><small>{day.toUpperCase()}</small></label>)}</div>
    </div>
    <div className="form-block"><div className="form-title"><span>02</span><div><h4>Choose your class times</h4><p>Live occupancy is shown for each group. Choose a preferred time and up to two alternatives.</p></div></div>
     {!wpConfigured&&<p className="inline-note">Preview mode: the 12 places shown are sample values, not live bookings. Connect the WordPress backend to display actual booked and remaining places.</p>}
     {loading?<p className="inline-note">Loading live class availability…</p>:null}
     {error?<p className="error-note">{error}</p>:null}
     <div className="availability-list">{selected.map(day=>{const atelier=atelierDays.find(a=>a[0]===day)?.[1]||day;return <div className="availability-atelier" key={day}><h5>{day.toUpperCase()} · {atelier}</h5><div className="slot-grid">{times.map(time=>{const slot=slotsFor(day).find(s=>s.time===time);const available=slot?slot.available:0;const full=slot?slot.status==="full":false;return <div className={`slot ${full?"slot-full":""} ${preferred[day]===time?"slot-selected":""}`} key={time}><label><input type="radio" name={`preferred-${day}`} disabled={full||loading} checked={preferred[day]===time} onChange={()=>choosePreferred(day,time)}/><b>{time}</b></label><span>{slot?`${available} places left · ${slot.booked}/${slot.capacity} booked`:"Availability unavailable"}</span><label className="alt-label"><input type="checkbox" disabled={full||preferred[day]===time} checked={(alternates[day]||[]).includes(time)} onChange={()=>toggleAlternate(day,time)}/> Alternative</label>{full&&<em>Fully booked</em>}</div>})}</div></div>})}
     {!selected.length&&<p className="inline-note">Select an atelier above to see its class groups and available places.</p>}
    </div>
    <div className="form-block"><div className="form-title"><span>03</span><div><h4>Your details</h4><p>Information required to process your enrolment.</p></div></div>
     <div className="fields-grid">
      <label>First name<input required value={form.first_name} onChange={e=>update("first_name",e.target.value)}/></label>
      <label>Last name<input required value={form.last_name} onChange={e=>update("last_name",e.target.value)}/></label>
      <label>Email address<input type="email" required value={form.email} onChange={e=>update("email",e.target.value)}/></label>
      <label>Telephone number<input required value={form.phone} onChange={e=>update("phone",e.target.value)}/></label>
      <label>Country of residence<input required value={form.country} onChange={e=>update("country",e.target.value)}/></label>
      <label>Date of birth<input type="date" required value={form.date_of_birth} onChange={e=>update("date_of_birth",e.target.value)}/></label>
      <label>English proficiency<select required value={form.proficiency} onChange={e=>update("proficiency",e.target.value)}><option value="">Choose your level</option>{["Beginner","Elementary","Intermediate","Upper-intermediate","Advanced"].map(x=><option key={x}>{x}</option>)}</select></label>
     </div>
     <div className="goals-wrap"><b>What would you like to improve?</b><div className="goals-grid">{goals.map(g=><label key={g}><input type="checkbox" checked={form.goals.includes(g)} onChange={e=>update("goals",e.target.checked?[...form.goals,g]:form.goals.filter(x=>x!==g))}/>{g}</label>)}</div></div>
     <label className="full-label">Tell us a little more about your learning goals (optional)<textarea rows={3} value={form.learning_goals} onChange={e=>update("learning_goals",e.target.value)}/></label>
    </div>
    <div className="form-block"><div className="form-title"><span>04</span><div><h4>Review your tuition</h4><p>Calculated from the current term session counts and selected ateliers.</p></div></div>
     <div className="price-summary">{selected.map(day=><div key={day}><span>{atelierDays.find(a=>a[0]===day)?.[1]} · {data.sessions?.[day]??0} sessions</span><b>€{((data.sessions?.[day]??0)*2*(data.hourly_rate||9.6)).toFixed(2)}</b></div>)}<div><span>Total teaching hours</span><b>{total.hours} hours</b></div><div><span>Tuition</span><b>€{total.tuition.toFixed(2)}</b></div><div><span>One-time workbook fee {selected.length?"(per student)":"(select an atelier)"}</span><b>€{(selected.length?data.workbook_fee:0).toFixed(2)}</b></div><div className="price-total"><span>Estimated total</span><b>€{total.total.toFixed(2)}</b></div></div>
     <p className="small-note">This is a first-enrolment estimate including the one-time workbook fee. Returning students who have already paid for the workbook will not be charged for it again. The WordPress backend recalculates the amount before creating the invoice.</p>
     <label className="terms-check"><input type="checkbox" checked={form.accept_terms} onChange={e=>update("accept_terms",e.target.checked)}/> I have read and accept the Academy's <a href="#terms">Fees & Terms</a>, including the applicable withdrawal and cancellation conditions.</label>
    </div>
    {error&&<p className="error-note">{error}</p>}
    {result&&<div className="success-note"><b>{result.message}</b>{result.student_id&&<span>Student ID: {result.student_id}</span>}{result.invoice_url&&<a href={result.invoice_url} target="_blank" rel="noreferrer">View invoice ↗</a>}</div>}
    <button className="button submit-button" disabled={submitting||loading}>{submitting?"Submitting…":"Submit registration and request invoice ↗"}</button>
    <p className="form-disclaimer">Submitting creates an enrolment request and invoice. A place is held temporarily while payment is pending; payment confirmation is handled by the Academy's payment provider.</p>
   </form>
  </div>
  <aside className="registration-aside"><span className="eyebrow">YOUR ENROLMENT</span><h3>At a glance</h3><div className="aside-line"><span>Selected ateliers</span><b>{selected.length}/4</b></div><div className="aside-line"><span>Weekly class hours</span><b>{selected.length*2}h</b></div><div className="aside-line"><span>Academic term</span><b>{term.replace("2026-27-","").replace("-"," ").toUpperCase()}</b></div><div className="aside-total"><span>Estimated total</span><strong>€{total.total.toFixed(2)}</strong></div><p>All class times use the Europe/Paris time zone. Places shown are refreshed from the Academy's booking backend.</p><div className="aside-help">Need private or corporate coaching? <a href="#contact">Contact the Academy ↗</a></div></aside>
 </div>;
}
