'use client';
import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { LockKeyhole, UserRound } from 'lucide-react';
import { CountryCodeDropdown } from '@/components/ui/CountryCodeDropdown';
import { TutorProfile } from './ProgrammeSummary';
import { EnrollmentFormats, EnrollmentGuarantee, EnrollmentIntro, EnrollmentProgramme } from './EnrollmentDetails';
import styles from './Enrollment.module.css';
import { WHATSAPP_URL } from './config';
import { ALGEBRA_PLANS, algebraPrice } from '@/lib/algebraOffer.mjs';

export default function AlgebraCheckout({ customer, enrollment, initialFormat = 'one_to_one' }) {
  const router = useRouter();
  const [context, setContext] = useState(enrollment || { groupOpen:false,timetables:[] });
  const [format, setFormat] = useState(initialFormat === 'group' ? 'group' : 'one_to_one');
  const [timetableId, setTimetableId] = useState('');
  const [groupMessage, setGroupMessage] = useState(false);
  const [countryCode, setCountryCode] = useState(customer?.country_code || '+1');
  const [phone, setPhone] = useState(customer?.phone_number || '');
  const [ready, setReady] = useState(false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState('');
  const plan = ALGEBRA_PLANS.find(p => p.format === format);
  const timetables = context.timetables.filter(t => t.format === format && t.confirmed && (!t.payment_status || t.payment_status === 'Pending'));
  const timetable = timetables.find(t => String(t.id) === timetableId) || (timetables.length === 1 ? timetables[0] : null);
  const unavailable = format === 'group' && !context.groupOpen;
  useEffect(() => {
    let active = true;
    const refresh = () => fetch('/api/algebra/enrollment', { cache:'no-store' }).then(async response => {
      const result = await response.json();
      if (!response.ok) throw new Error(result.message);
      if (active) setContext(result);
    }).catch(e => { if (active) { setContext({ groupOpen:false,timetables:[] });setError(e.message || 'Please contact Aisha to confirm availability.'); } });
    refresh();window.addEventListener('focus',refresh);
    const interval = setInterval(refresh,30000);
    return () => { active = false;window.removeEventListener('focus',refresh);clearInterval(interval); };
  }, []);
  useEffect(() => {
    if (window.Razorpay) { queueMicrotask(() => setReady(true));return; }
    const script = document.createElement('script');script.src='https://checkout.razorpay.com/v1/checkout.js';script.async=true;
    script.onload=() => setReady(true);script.onerror=() => setError('Could not load secure payment. Reload or contact Aisha.');document.body.appendChild(script);
    return () => script.remove();
  }, []);
  async function pay(event) {
    event.preventDefault();setError('');
    if (unavailable) { setGroupMessage(true);return; }
    if (!timetable || !ready || busy) return;
    const accepted = new FormData(event.currentTarget).get('terms') === 'on';
    setBusy(true);
    try {
      const response = await fetch('/api/checkout/create-order', { method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({ slug:'algebra-1-tutoring',plan_id:plan.id,timetable_id:timetable.id,enrollment_terms_accepted:accepted,first_name:customer.first_name,last_name:customer.last_name,email:customer.email,phone:`${countryCode} ${phone}` }) });
      const order = await response.json();
      if (!response.ok) throw new Error(order.message || 'Could not start payment.');
      if (Number(order.amount) !== plan.amount * 100 || order.currency !== 'USD') throw new Error('The offer has changed. Reload and review the total before payment.');
      const checkout = new window.Razorpay({ key:order.key,order_id:order.order_id,amount:order.amount,currency:order.currency,
        name:'Cambridge Veritas',description:`${plan.name} · 46 × 60-minute Algebra I lessons · one-time payment`,prefill:order.prefill,theme:{color:'#731F32'},
        handler:async payment => {
          try {
            const result = await fetch('/api/checkout/verify-payment', { method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payment) });
            const verified = await result.json();
            if (!result.ok || !verified.success) throw new Error(verified.message || 'Payment confirmation is pending. Contact support with your payment reference.');
            router.push(verified.next_url);
          } catch(e) { setError(e.message);setBusy(false); }
        },modal:{ondismiss:() => setBusy(false)} });
      checkout.on('payment.failed',payment => { setError(payment.error?.description || 'Payment failed. Please try again.');setBusy(false); });checkout.open();
    } catch(e) { setError(e.message);setBusy(false); }
  }
  return <div className={styles.layout}>
    <div className={styles.overview}>
      <EnrollmentIntro />
      <EnrollmentFormats format={format} groupOpen={context.groupOpen} showClosedMessage={groupMessage} onSelect={nextFormat => {
        if (nextFormat === 'group' && !context.groupOpen) { setGroupMessage(true);return; }
        setFormat(nextFormat);setTimetableId('');setGroupMessage(false);
      }} />
      <EnrollmentGuarantee />
    </div>
    <aside className={styles.accountPanel} aria-label="Confirm enrollment and payment">
      <div className={styles.accountCard}>
        <div className={styles.accountHeading}><span><UserRound size={16} aria-hidden="true" /></span><p>YOUR FAMILY’S ENROLLMENT</p></div>
        <div className={styles.orderPreview}><div><span>46 live one-hour lessons</span><strong>{plan.name}</strong></div><div><strong>{algebraPrice(plan.amount)}</strong><span>paid once{format === 'group' ? ' per child' : ''}</span></div></div>
        <form key={`${format}-${timetable?.id || ''}`} onSubmit={pay} className={styles.checkoutForm}>
          <h2>Confirm enrollment details</h2><p>Parent account: {customer.email}</p>
          <label>Agreed family timetable<select value={timetable?.id || ''} onChange={e => setTimetableId(e.target.value)} required disabled={unavailable}><option value="">Choose your confirmed timetable</option>{timetables.map(t => <option key={t.id} value={t.id}>{t.child_name} · Grade {t.grade} · {t.tutor.name} · starts {t.lessons[0]?.replace('T',' ')}</option>)}</select></label>
          {timetable?.tutor ? <div className={styles.tutors}><TutorProfile tutor={timetable.tutor} /><a href="#confirmed-algebra-lessons">Review all 46 confirmed lesson times ↓</a></div> : null}
          {!timetable ? <p>Before payment, Aisha will introduce your tutor and agree all 46 lesson times with you. Enrollment is accepted only when the whole programme fits. <a href={WHATSAPP_URL} target="_blank" rel="noreferrer">Confirm a timetable with Aisha</a>.</p> : null}
          <label>Contact phone<span className={styles.phone}><CountryCodeDropdown value={countryCode} onChange={setCountryCode} /><input type="tel" required value={phone} onChange={e => setPhone(e.target.value.replace(/[^\d\s()-]/g,''))} autoComplete="tel-national" /></span></label>
          <label className={styles.consent}><input name="terms" type="checkbox" required /><span>I have reviewed the tutor, all 46 one-hour lesson times in Central Time, the complete programme and the {algebraPrice(plan.amount)} one-time price. I accept the <a href="/algebra-privacy#terms">terms</a> and <a href="/algebra-privacy#refund">first-week full-refund guarantee and subsequent refund terms</a>.</span></label>
          {error ? <p role="alert" className={styles.error}>{error}</p> : null}
          <button type="submit" disabled={busy || !ready || !timetable || unavailable} className={styles.payButton}>{busy ? 'Confirming payment…' : `Pay ${algebraPrice(plan.amount)} once · ${plan.name}`}</button>
          <p className={styles.paymentHint}>First-week money-back protection.<br />Payment unlocks once your tutor and timetable are confirmed.</p>
        </form>
        <p className={styles.noPayment}><LockKeyhole size={13} aria-hidden="true" /> Secure one-time payment through Razorpay.</p>
      </div>
    </aside>
    <div className={styles.programmeDetails}>
      <EnrollmentProgramme />
      {timetable?.lessons?.length ? <details id="confirmed-algebra-lessons" className={styles.confirmedLessons} open><summary>Your 46 confirmed lesson times · Central Time</summary><ol>{timetable.lessons.map((lesson, i) => <li key={`${i}-${lesson}`}>{lesson.replace('T', ' ')} · 60 min</li>)}</ol></details> : null}
    </div>
  </div>;
}
