'use client';

import { useState, useEffect, useRef } from 'react';
import Link from 'next/link';

/* ─── Types ──────────────────────────────────────────────────────── */
interface HeroStat    { value: string; label: string; icon?: string; }
interface SchoolHero  { eyebrow: string; title: string; subtitle: string; bg_image_url?: string; right_image_url?: string; right_caption?: string; stats: HeroStat[]; }
interface SchoolAbout { eyebrow: string; heading: string; body: string; bullets: string[]; image_url?: string; badge_text?: string; }
interface PastCourse  { id: number; image_url?: string; month_year: string; participants: number; title: string; slug?: string; has_pdfs?: boolean; }
interface UpcomingCourse { id: number; year: number; date_label: string; title: string; seats_left: number; enrol_url?: string; }
interface CalendarEntry  { id: number; year: number; month: number; date_range?: string; title: string; }
interface GalleryItem    { id: number; image_url: string; alt?: string; }
interface CalendarDownload { title?: string; subtitle?: string; button_label?: string; file_url: string; }
interface SchoolContact   { heading?: string; subtitle?: string; tag?: string; phone?: string; secondary_phone?: string; whatsapp?: string; email?: string; secondary_email?: string; location?: string; cta_label?: string; }

/* ─── Fallback data (matches screenshot) ─────────────────────────── */
const FALLBACK_HERO: SchoolHero = {
  eyebrow: 'COVER PHOTO',
  title: 'Industry-ready talent, guided by science.',
  subtitle: 'Fully residential programs bridging classroom science with real farm application.',
  right_caption: 'Integrated campus field exposure',
  stats: [
    { value: '500+',    label: 'Inductees trained',   icon: 'fas fa-user-graduate' },
    { value: '30+',     label: 'Projects conducted',  icon: 'fas fa-folder-open'   },
    { value: '15–25 yrs', label: 'Age covered',       icon: 'fas fa-clock'         },
    { value: '360°',    label: 'Residential Program',  icon: 'fas fa-rotate'        },
  ],
};

const FALLBACK_ABOUT: SchoolAbout = {
  eyebrow: 'ABOUT THE SCHOOL',
  heading: 'Bridging the gap between science and the farm.',
  body: 'Agrivet School offers fully residential, intensive training programs across broiler, layer, breeder, and aquaculture verticals. Our instructors bring 15–25 years of field experience, and each cohort is designed to shift professionals toward solution-oriented, evidence-based thinking.',
  bullets: [
    'Connecting classroom learning with practice field application.',
    'Combining technical skills with business ethics.',
    'Promoting evidence-based, sustainable livestock development.',
  ],
  badge_text: '360° Residential Program',
};

const FALLBACK_PAST: PastCourse[] = [
  { id: 1, month_year: 'MARCH 2025',    participants: 21, title: 'Broiler Farm Management Intensive' },
  { id: 2, month_year: 'JANUARY 2025',  participants: 18, title: 'Layer & Egg Quality Management'    },
  { id: 3, month_year: 'NOVEMBER 2024', participants: 29, title: 'Aquaculture Nutrition & Health'     },
];

const FALLBACK_UPCOMING: UpcomingCourse[] = [
  { id: 1, year: 2026, date_label: 'July 13–19, 2026',    title: 'Broiler Integration & Feed Mill Operations',    seats_left: 9  },
  { id: 2, year: 2026, date_label: 'August 4–9, 2026',    title: 'Poultry Disease Management & Biosecurity',      seats_left: 14 },
  { id: 3, year: 2026, date_label: 'September 1–5, 2026', title: 'Layer Farm Business & Economics',               seats_left: 20 },
  { id: 4, year: 2026, date_label: 'October 6–10, 2026',  title: 'Aqua Research & Sustainable Practices',         seats_left: 18 },
];

const FALLBACK_CALENDAR: CalendarEntry[] = [
  { id: 1, year: 2026, month: 7,  title: 'Broiler Integration' },
  { id: 2, year: 2026, month: 8,  title: 'Disease Mgmt'        },
  { id: 3, year: 2026, month: 9,  title: 'Layer Business'       },
  { id: 4, year: 2026, month: 10, title: 'Aqua Research'        },
];

const MONTH_NAMES = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'];

/* ─── Skeleton helpers ───────────────────────────────────────────── */
function Skel({ w = '100%', h = '1rem', className = '' }: { w?: string; h?: string; className?: string }) {
  return <span className={`sch-skeleton ${className}`} style={{ display: 'block', width: w, height: h }} />;
}

/* ─── Page ───────────────────────────────────────────────────────── */
export default function SchoolPage() {
  const API = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost/agrivet_web/backend';

  const [hero,     setHero]     = useState<SchoolHero | null>(null);
  const [about,    setAbout]    = useState<SchoolAbout | null>(null);
  const [past,     setPast]     = useState<PastCourse[]>([]);
  const [upcoming, setUpcoming] = useState<UpcomingCourse[]>([]);
  const [calendar, setCalendar] = useState<CalendarEntry[]>([]);
  const [gallery,      setGallery]      = useState<GalleryItem[]>([]);
  const [calDownload,  setCalDownload]  = useState<CalendarDownload | null>(null);
  const [contact,      setContact]      = useState<SchoolContact | null>(null);
  const [enrollOpen,      setEnrollOpen]      = useState(false);
  const [enrollCourse,    setEnrollCourse]    = useState('');
  const [enrollState,     setEnrollState]     = useState<'idle'|'sending'|'done'|'error'>('idle');
  const [courseDropOpen,  setCourseDropOpen]  = useState(false);
  const enrollFormRef  = useRef<HTMLFormElement>(null);
  const pastTrackRef   = useRef<HTMLDivElement>(null);

  const [loadingHero,     setLoadingHero]     = useState(true);
  const [loadingAbout,    setLoadingAbout]    = useState(true);
  const [loadingPast,     setLoadingPast]     = useState(true);
  const [loadingUpcoming, setLoadingUpcoming] = useState(true);
  const [loadingCalendar, setLoadingCalendar] = useState(true);
  const [loadingGallery,  setLoadingGallery]  = useState(true);

  useEffect(() => {
    fetch(`${API}/api/school/hero`)
      .then(r => r.json())
      .then(res => { if (res.success && res.data) setHero(res.data); else setHero(FALLBACK_HERO); })
      .catch(() => setHero(FALLBACK_HERO))
      .finally(() => setLoadingHero(false));

    fetch(`${API}/api/school/about`)
      .then(r => r.json())
      .then(res => { if (res.success && res.data) setAbout(res.data); else setAbout(FALLBACK_ABOUT); })
      .catch(() => setAbout(FALLBACK_ABOUT))
      .finally(() => setLoadingAbout(false));

    fetch(`${API}/api/school/past-courses`)
      .then(r => r.json())
      .then(res => {
        if (res.success && Array.isArray(res.data) && res.data.length) setPast(res.data);
        else setPast(FALLBACK_PAST);
        setTimeout(() => { if (pastTrackRef.current) pastTrackRef.current.scrollLeft = 0; }, 50);
      })
      .catch(() => setPast(FALLBACK_PAST))
      .finally(() => setLoadingPast(false));

    fetch(`${API}/api/school/upcoming-courses`)
      .then(r => r.json())
      .then(res => { if (res.success && Array.isArray(res.data) && res.data.length) setUpcoming(res.data); else setUpcoming(FALLBACK_UPCOMING); })
      .catch(() => setUpcoming(FALLBACK_UPCOMING))
      .finally(() => setLoadingUpcoming(false));

    fetch(`${API}/api/school/calendar`)
      .then(r => r.json())
      .then(res => { if (res.success && Array.isArray(res.data) && res.data.length) setCalendar(res.data); else setCalendar(FALLBACK_CALENDAR); })
      .catch(() => setCalendar(FALLBACK_CALENDAR))
      .finally(() => setLoadingCalendar(false));

    fetch(`${API}/api/school/gallery`)
      .then(r => r.json())
      .then(res => { if (res.success && Array.isArray(res.data)) setGallery(res.data); })
      .catch(() => {})
      .finally(() => setLoadingGallery(false));

    fetch(`${API}/api/school/calendar-download`)
      .then(r => r.json())
      .then(res => { if (res.success && res.data) setCalDownload(res.data); })
      .catch(() => {});

    fetch(`${API}/api/school/contact`)
      .then(r => r.json())
      .then(res => { if (res.success && res.data) setContact(res.data); })
      .catch(() => {});
  }, []);

  /* derived: active hero + about (resolved data) */
  const h = hero  ?? FALLBACK_HERO;
  const a = about ?? FALLBACK_ABOUT;

  async function submitEnroll(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setEnrollState('sending');
    const fd = new FormData(e.currentTarget);
    try {
      const res = await fetch(`${API}/api/leads`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify({
          name:    fd.get('name'),
          phone:   fd.get('phone'),
          email:   fd.get('email'),
          message: fd.get('message'),
          course:  fd.get('course'),
          source:  'school',
        }),
      });
      const json = await res.json();
      if (json.success) { setEnrollState('done'); enrollFormRef.current?.reset(); }
      else setEnrollState('error');
    } catch { setEnrollState('error'); }
  }

  /* calendar: build year → Map<month, entries[]> */
  const calYear = calendar.length ? calendar[0].year : 2026;
  const calMap  = new Map<number, CalendarEntry[]>();
  calendar.filter(e => e.year === calYear).forEach(e => {
    const arr = calMap.get(e.month) ?? [];
    arr.push(e);
    calMap.set(e.month, arr);
  });

  /* upcoming: group by year for the heading */
  const upYear = upcoming.length ? upcoming[0].year : 2026;

  return (
    <>
      {/* ── Split Hero ─────────────────────────────────────────── */}
      <div className="sch-split-hero">
        <div
          className="sch-split-left"
          style={h.bg_image_url ? { backgroundImage: `url('${h.bg_image_url}')`, backgroundSize: 'cover', backgroundPosition: 'center' } : undefined}
        >
          <div className="sch-split-left-inner">
            {loadingHero ? (
              <>
                <Skel w="120px" h=".75rem" className="mb-3" />
                <Skel w="90%"  h="2.5rem" className="mb-2" />
                <Skel w="70%"  h="2.5rem" className="mb-4" />
                <Skel w="85%"  h="1rem"   className="mb-2" />
                <Skel w="70%"  h="1rem" />
              </>
            ) : (
              <>
                <p className="sch-hero-eyebrow">{h.eyebrow}</p>
                <h1 dangerouslySetInnerHTML={{ __html: h.title.replace(/,/, ',<br/>') }} />
                {h.subtitle && <p className="sch-hero-sub">{h.subtitle}</p>}
              </>
            )}
          </div>
        </div>

        <div className="sch-split-right">
          {h.right_image_url
            ? <img src={h.right_image_url} alt="Agrivet School campus" />
            : <img src="/images/school-background.webp" alt="Agrivet School campus" />
          }
          {h.right_caption && (
            <div className="sch-split-right-caption">{h.right_caption}</div>
          )}
        </div>
      </div>

      {/* ── Stats bar ──────────────────────────────────────────── */}
      <div className="sch-stats-bar">
        <div className="sch-stats-inner">
          {(loadingHero ? FALLBACK_HERO.stats : h.stats ?? FALLBACK_HERO.stats).map((s, i) => (
            <div key={i} className="sch-stat">
              {s.icon && <i className={`${s.icon} sch-stat-icon`} aria-hidden="true" />}
              <div className="sch-stat-text">
                <span className="sch-stat-value">{s.value}</span>
                <span className="sch-stat-label">{s.label}</span>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* ── About the School ───────────────────────────────────── */}
      <section className="sch-about-section">
        <div className="container">
          {loadingAbout ? (
            <div className="sch-about-inner">
              <div>
                <Skel w="140px" h=".75rem" className="mb-3" />
                <Skel w="80%"   h="2rem"   className="mb-2" />
                <Skel w="60%"   h="2rem"   className="mb-4" />
                <Skel w="100%"  h="1rem"   className="mb-2" />
                <Skel w="95%"   h="1rem"   className="mb-2" />
                <Skel w="88%"   h="1rem"   className="mb-4" />
              </div>
              <Skel w="100%" h="360px" />
            </div>
          ) : (
            <div className="sch-about-inner">
              <div>
                <p className="sch-about-eyebrow">{a.eyebrow}</p>
                <h2 className="sch-about-h2">{a.heading}</h2>
                {a.body && <p className="sch-about-body">{a.body}</p>}
                {(a.bullets ?? []).length > 0 && (
                  <ul className="sch-about-bullets">
                    {(a.bullets ?? []).map((b, i) => <li key={i}>{b}</li>)}
                  </ul>
                )}
              </div>
              <div className="sch-about-img-wrap">
                <img
                  src={a.image_url || '/images/mission.webp'}
                  alt="Agrivet School classroom"
                />
                {a.badge_text && <span className="sch-about-badge">{a.badge_text}</span>}
              </div>
            </div>
          )}
        </div>
      </section>

      {/* ── Past Courses ───────────────────────────────────────── */}
      <section className="sch-past-section">
        <div className="container">
          <div className="sch-section-head">
            <h2 className="sch-section-h2">Past Courses</h2>
            <div className="sch-carousel-arrows">
              <button className="sch-carousel-btn" aria-label="Previous" onClick={() => pastTrackRef.current?.scrollBy({ left: -320, behavior: 'smooth' })}>
                <i className="fas fa-chevron-left" />
              </button>
              <button className="sch-carousel-btn" aria-label="Next" onClick={() => pastTrackRef.current?.scrollBy({ left: 320, behavior: 'smooth' })}>
                <i className="fas fa-chevron-right" />
              </button>
            </div>
          </div>

          <div className="sch-past-carousel-wrap">
            <div className="sch-past-track" ref={pastTrackRef}>
              {loadingPast
                ? [1, 2, 3, 4].map(i => (
                    <div key={i} className="sch-past-card">
                      <Skel w="100%" h="200px" />
                      <div style={{ padding: '1.1rem 1.25rem 1.35rem' }}>
                        <Skel w="70%" h=".75rem" className="mb-2" />
                        <Skel w="90%" h="1.1rem" />
                      </div>
                    </div>
                  ))
                : past.map(course => {
                    const inner = (
                      <>
                        <img
                          className="sch-past-img"
                          src={course.image_url || '/images/agrivet-research.webp'}
                          alt={course.title}
                        />
                        <div className="sch-past-body">
                          <p className="sch-past-meta">{course.month_year}</p>
                          <h3 className="sch-past-title">{course.title}</h3>
                          {course.has_pdfs && (
                            <span className="sch-past-pdf-badge"><i className="fas fa-file-pdf" /> Course Materials</span>
                          )}
                        </div>
                      </>
                    );
                    return course.slug && course.has_pdfs ? (
                      <Link key={course.id} href={`/school/past-courses/${course.slug}`} className="sch-past-card sch-past-card--link">
                        {inner}
                      </Link>
                    ) : (
                      <div key={course.id} className="sch-past-card">
                        {inner}
                      </div>
                    );
                  })}
            </div>
          </div>
        </div>
      </section>

      {/* ── Upcoming Courses ───────────────────────────────────── */}
      <section className="sch-upcoming-section">
        <div className="container" style={{ position: 'relative' }}>
          <div className="sch-upcoming-head">
            <h2 className="sch-upcoming-h2">Upcoming {upYear}</h2>
            {/* <button type="button" className="sch-reg-badge" onClick={() => { setEnrollCourse(''); setEnrollState('idle'); setEnrollOpen(true); }}>Registration in Progress</button> */}
          </div>

          {loadingUpcoming ? (
            <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
              {[1, 2, 3, 4].map(i => <Skel key={i} w="100%" h="56px" />)}
            </div>
          ) : (
            <div className="sch-upcoming-list">
              {upcoming.map(course => (
                <div key={course.id} className="sch-upcoming-row">
                  <span className="sch-upcoming-date">{course.date_label}</span>
                  <span className="sch-upcoming-title">{course.title}</span>
                </div>
              ))}
            </div>
          )}
        </div>
      </section>

      {/* ── Calendar ───────────────────────────────────────────── */}
      <section className="sch-calendar-section">
        <div className="container">
          <div className="sch-section-head" style={{ borderBottomColor: '#d8e4dc' }}>
            <h2 className="sch-section-h2">Calendar {calYear}</h2>
            {calDownload?.file_url && (
              <a href={calDownload.file_url} download target="_blank" rel="noopener noreferrer" className="sch-cal-dl-btn" title="Download Calendar">
                <i className="fas fa-download" /> {calDownload.button_label || 'Download Calendar'}
              </a>
            )}
          </div>

          {loadingCalendar ? (
            <Skel w="100%" h="280px" />
          ) : (
            <div className="sch-cal-grid">
              {MONTH_NAMES.map((name, idx) => {
                const monthNum = idx + 1;
                const entries  = calMap.get(monthNum) ?? [];
                return (
                  <div key={monthNum} className={`sch-cal-cell${entries.length ? ' sch-cal-active' : ''}`}>
                    <span className="sch-cal-month">{name}</span>
                    {entries.map((entry, i) => (
                      <div key={i} className="sch-cal-entry">
                        {entry.date_range && <span className="sch-cal-range">{entry.date_range}</span>}
                        <span className="sch-cal-course">{entry.title}</span>
                      </div>
                    ))}
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </section>

      {/* ── Life at Agrivet School ─────────────────────────────── */}
      {(loadingGallery || gallery.length > 0) && (
        <section className="sch-life-section">
          <div className="container">
            <div className="sch-section-head" style={{ borderBottomColor: '#d8e4dc' }}>
              <h2 className="sch-section-h2">Life at Agrivet School</h2>
            </div>
          </div>
          <div className="sch-life-track-wrap">
            {loadingGallery ? (
              <div className="sch-life-track" style={{ animationPlayState: 'paused' }}>
                {[1,2,3,4,5,6].map(i => <div key={i} className="sch-life-card sch-skeleton" />)}
              </div>
            ) : (
              <div className="sch-life-track" style={{ animationDuration: '55s' }}>
                {[...gallery, ...gallery].map((img, i) => (
                  <div key={i} className="sch-life-card">
                    <img src={img.image_url} alt={img.alt || 'Life at Agrivet School'} loading="lazy" />
                  </div>
                ))}
              </div>
            )}
          </div>
        </section>
      )}

      {/* ── Get in Touch ───────────────────────────────────────── */}
      {contact && (
        <section className="sch-git-section">
          <div className="container">
            <div className="sch-git-inner">

              {/* Left */}
              <div className="sch-git-left">
                <h2 className="sch-git-heading">{contact.heading || 'Get in Touch'}</h2>
                {contact.subtitle && <p className="sch-git-subtitle">{contact.subtitle}</p>}
                {contact.tag && <span className="sch-git-tag">{contact.tag}</span>}
              </div>

              {/* Middle — contact info */}
              <div className="sch-git-info">
                {(contact.phone || contact.secondary_phone) && (
                  <div className="sch-git-info-row">
                    <i className="fas fa-phone-alt sch-git-info-icon" />
                    <div className="sch-git-info-vals">
                      {contact.phone           && <a href={`tel:${contact.phone.replace(/\s/g,'')}`}>{contact.phone}</a>}
                      {contact.secondary_phone && <a href={`tel:${contact.secondary_phone.replace(/\s/g,'')}`}>{contact.secondary_phone}</a>}
                    </div>
                  </div>
                )}
                {(contact.email || contact.secondary_email) && (
                  <div className="sch-git-info-row">
                    <i className="fas fa-envelope sch-git-info-icon" />
                    <div className="sch-git-info-vals">
                      {contact.email           && <a href={`mailto:${contact.email}`}>{contact.email}</a>}
                      {contact.secondary_email && <a href={`mailto:${contact.secondary_email}`} className="sch-git-info-secondary">{contact.secondary_email}</a>}
                    </div>
                  </div>
                )}
                {contact.location && (
                  <div className="sch-git-info-row">
                    <i className="fas fa-map-marker-alt sch-git-info-icon" />
                    <div className="sch-git-info-vals">
                      <span>{contact.location}</span>
                    </div>
                  </div>
                )}
              </div>

              {/* Right — CTA */}
              {/* <div className="sch-git-cta">
                <button
                  type="button"
                  className="sch-git-btn"
                  onClick={() => { setEnrollCourse(''); setEnrollState('idle'); setEnrollOpen(true); }}
                >
                  {contact.cta_label || 'Register Interest'} <i className="fas fa-arrow-right" />
                </button>
              </div> */}

            </div>
          </div>
        </section>
      )}

      {/* ── Enrollment Modal ───────────────────────────────────── */}
      {enrollOpen && (
        <div className="enroll-modal-backdrop" onClick={() => setEnrollOpen(false)}>
          <div className="enroll-modal-box" onClick={e => e.stopPropagation()}>
            <button className="enroll-modal-close" onClick={() => setEnrollOpen(false)} aria-label="Close">
              <i className="fas fa-xmark" />
            </button>

            <div className="enroll-modal-head">
              <img
                src={`${process.env.NEXT_PUBLIC_BASE_PATH ?? ''}/images/agrivet-logo.webp`}
                alt="Agrivet"
                className="enroll-modal-logo"
              />
              <h2>Registration in Progress</h2>
              <p className="enroll-modal-sub">Fill in your details and we'll get back to you within 24 hours.</p>
            </div>

            {enrollState === 'done' ? (
              <div className="enroll-success">
                <i className="fas fa-circle-check" />
                <p>Thank you! We'll be in touch shortly.</p>
                <button className="enroll-submit-btn" onClick={() => setEnrollOpen(false)}>Close</button>
              </div>
            ) : (
              <form className="enroll-form" ref={enrollFormRef} onSubmit={submitEnroll}>
                <div className="enroll-field-row">
                  <div className="enroll-field">
                    <label>Full Name <span>*</span></label>
                    <input type="text" name="name" required placeholder="Your name" />
                  </div>
                  <div className="enroll-field">
                    <label>Phone <span>*</span></label>
                    <input type="tel" name="phone" required placeholder="+91 XXXXX XXXXX" />
                  </div>
                </div>
                <div className="enroll-field">
                  <label>Email</label>
                  <input type="email" name="email" placeholder="you@example.com" />
                </div>
                <div className="enroll-field">
                  <label>Course Interested In</label>
                  <input type="hidden" name="course" value={enrollCourse} />
                  <div className="enroll-custom-select">
                    <button
                      type="button"
                      className="enroll-select-trigger"
                      onClick={() => setCourseDropOpen(o => !o)}
                    >
                      <span>{enrollCourse || 'General Enquiry'}</span>
                      <i className={`fas fa-chevron-${courseDropOpen ? 'up' : 'down'}`} />
                    </button>
                    {courseDropOpen && (
                      <ul className="enroll-select-list">
                        <li className={!enrollCourse ? 'selected' : ''} onClick={() => { setEnrollCourse(''); setCourseDropOpen(false); }}>General Enquiry</li>
                        {upcoming.map(c => (
                          <li key={c.id} className={enrollCourse === c.title ? 'selected' : ''} onClick={() => { setEnrollCourse(c.title); setCourseDropOpen(false); }}>{c.title}</li>
                        ))}
                      </ul>
                    )}
                  </div>
                </div>
                <div className="enroll-field">
                  <label>Message</label>
                  <textarea name="message" rows={3} placeholder="Any questions or specific requirements…" />
                </div>
                {enrollState === 'error' && (
                  <p className="enroll-error">Something went wrong. Please try again.</p>
                )}
                <button type="submit" className="enroll-submit-btn" disabled={enrollState === 'sending'}>
                  {enrollState === 'sending' ? <><i className="fas fa-spinner fa-spin mr-1" /> Sending…</> : <>Submit Enquiry <i className="fas fa-arrow-right" /></>}
                </button>
              </form>
            )}
          </div>
        </div>
      )}
    </>
  );
}
