import React, { useMemo, useState } from 'react'
import { Helmet } from 'react-helmet-async'
import { Link } from 'react-router-dom'
import { EventCard } from '../components/Cards'
import { useEvents } from '../hooks/useEvents'

const filters = ['All', 'This Month', 'Next Month', 'Family', 'Outreach']

function isSameMonth(dateStr, baseDate) {
  const date = new Date(dateStr)
  if (Number.isNaN(date)) return false
  return (
    date.getFullYear() === baseDate.getFullYear() &&
    date.getMonth() === baseDate.getMonth()
  )
}

function filterEvents(events, activeFilter) {
  const now = new Date()
  if (activeFilter === 'All') {
    return events
  }

  if (activeFilter === 'This Month') {
    return events.filter(event => isSameMonth(event.date, now))
  }

  if (activeFilter === 'Next Month') {
    const nextMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1)
    return events.filter(event => isSameMonth(event.date, nextMonth))
  }

  const category = activeFilter.toLowerCase()
  return events.filter(event => (event.category || '').toLowerCase().includes(category))
}

function getValidDate(event) {
  const date = new Date(event.date)
  return Number.isNaN(date.getTime()) ? null : date
}

function formatEventDate(dateStr) {
  const date = new Date(dateStr)
  if (Number.isNaN(date.getTime())) return dateStr || 'Date TBA'
  return date.toLocaleDateString(undefined, {
    weekday: 'long',
    month: 'long',
    day: 'numeric',
    year: 'numeric',
  })
}

function formatEventTime(timeStr) {
  if (!timeStr) return 'Time TBA'
  return timeStr
}

export default function Events() {
  const [active, setActive] = useState('All')
  const { events, loading, error } = useEvents(true)

  const futureEvents = useMemo(() => {
    const today = new Date()
    today.setHours(0, 0, 0, 0)
    return events.filter(event => {
      const date = new Date(event.date)
      if (Number.isNaN(date.getTime())) return true
      return date >= today
    })
  }, [events])

  const actionableEvents = useMemo(
    () => futureEvents.filter(event => Boolean(getValidDate(event))),
    [futureEvents]
  )

  const nextEvent = useMemo(() => {
    if (actionableEvents.length > 0) {
      return actionableEvents
        .slice()
        .sort((a, b) => getValidDate(a) - getValidDate(b))[0]
    }
    return futureEvents[0] || null
  }, [actionableEvents, futureEvents])

  const upcomingEvents = useMemo(
    () => filterEvents(futureEvents, active),
    [futureEvents, active]
  )

  const totalUpcoming = futureEvents.length
  const familyCount = futureEvents.filter(event => (event.category || '').toLowerCase().includes('family')).length
  const outreachCount = futureEvents.filter(event => (event.category || '').toLowerCase().includes('outreach')).length

  const nextEventDate = nextEvent ? formatEventDate(nextEvent.date) : null
  const nextEventTime = nextEvent ? formatEventTime(nextEvent.time) : null

  return (
    <>
      <Helmet><title>Events | Annaville SDA Church</title></Helmet>

      <section className="bg-gradient-to-r from-primary/10 via-sand/20 to-white py-16 md:py-20">
        <div className="container grid gap-10 lg:grid-cols-[1.6fr,1fr] items-center">
          <div className="space-y-6">
            <p className="text-xs uppercase tracking-[0.35em] text-primary font-semibold">
              Gather. Serve. Grow.
            </p>
            <h1 className="font-heading text-display30 text-ink">
              Upcoming Events & Community Moments
            </h1>
            <p className="text-body text-muted max-w-2xl">
              There is always something happening at Annaville SDA Church. Explore ways to worship, volunteer,
              and connect with families throughout the Corpus Christi community.
            </p>
            <div className="grid gap-6 sm:grid-cols-3">
              <div>
                <p className="font-heading text-display20 text-primary">
                  {totalUpcoming}
                </p>
                <p className="text-muted text-sm">Upcoming gatherings</p>
              </div>
              <div>
                <p className="font-heading text-display20 text-primary">
                  {familyCount}
                </p>
                <p className="text-muted text-sm">Family-focused events</p>
              </div>
              <div>
                <p className="font-heading text-display20 text-primary">
                  {outreachCount}
                </p>
                <p className="text-muted text-sm">Community outreach</p>
              </div>
            </div>
          </div>

          <div className="bg-white/80 backdrop-blur rounded-2xl shadow-level1 p-6 md:p-8 space-y-4">
            {nextEvent ? (
              <>
                <span className="text-xs uppercase tracking-[0.3em] text-primary font-semibold">Next gathering</span>
                <h2 className="font-heading text-h3 text-ink">{nextEvent.title}</h2>
                <div className="space-y-1 text-sm text-muted">
                  <div>{nextEventDate}</div>
                  <div>{nextEventTime}{nextEvent.location ? ` - ${nextEvent.location}` : ''}</div>
                </div>
                <p className="text-body text-sm text-muted line-clamp-3">
                  {nextEvent.description || 'We would love for you to join us. Everyone is welcome!'}
                </p>
                <Link to={`/events/${nextEvent.slug}`} className="btn w-full sm:w-auto">
                  View Event Details
                </Link>
              </>
            ) : (
              <div className="space-y-3">
                <h2 className="font-heading text-h3 text-ink">Check back soon</h2>
                <p className="text-muted text-sm">
                  We are finalizing new activities and will post them here shortly. Stay tuned!
                </p>
              </div>
            )}
          </div>
        </div>
      </section>

      <section className="section -mt-10 md:-mt-14">
        <div className="container">
          <div className="bg-white rounded-2xl shadow-level1 p-6 md:p-10">
            <div className="flex flex-wrap items-center justify-between gap-6 mb-8">
              <h2 className="font-heading text-h3 text-ink mb-2 md:mb-0">Browse Events</h2>
              <div className="flex gap-3 flex-wrap">
                {filters.map(filter => (
                  <button
                    key={filter}
                    className={`chip ${active === filter ? 'bg-primary text-white shadow-level1 border border-primary' : ''}`}
                    aria-pressed={active === filter}
                    onClick={() => setActive(filter)}
                  >
                    {filter}
                  </button>
                ))}
              </div>
            </div>

            <div className="min-h-[200px]">
              {loading && (
                <p className="text-muted">Loading events...</p>
              )}
              {error && !loading && (
                <p className="text-red-600">Unable to load events right now. Please try again later.</p>
              )}
              {!loading && !error && upcomingEvents.length === 0 && (
                <div className="bg-sand/40 border border-subtle rounded-xl p-8 text-center text-muted">
                  No upcoming events match this filter. Try another category or check back soon.
                </div>
              )}
              {!loading && !error && upcomingEvents.length > 0 && (
                <div className="grid gap-10 md:grid-cols-3">
                  {upcomingEvents.map(event => (
                    <EventCard key={event.slug} e={event} />
                  ))}
                </div>
              )}
            </div>
          </div>
        </div>
      </section>
    </>
  )
}
