'use client'

import { useState, useEffect } from 'react'
import { motion } from 'framer-motion'
import { Calendar, Clock, MapPin, ArrowRight, Sparkles } from 'lucide-react'
import Link from 'next/link'
import { eventsApi, Event } from '@/lib/api'

const categoryColors: Record<string, string> = {
  Community: 'bg-blue-500/20 text-blue-300 border-blue-500/30',
  'Public Hearing': 'bg-red-500/20 text-red-300 border-red-500/30',
  Cultural: 'bg-purple-500/20 text-purple-300 border-purple-500/30',
  Workshop: 'bg-green-500/20 text-green-300 border-green-500/30',
  'Council Meeting': 'bg-orange-500/20 text-orange-300 border-orange-500/30',
  General: 'bg-gray-500/20 text-gray-300 border-gray-500/30',
}

const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  const today = new Date()
  const tomorrow = new Date(today)
  tomorrow.setDate(tomorrow.getDate() + 1)
  
  const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
  
  const dayName = days[date.getDay()]
  const day = date.getDate()
  const month = months[date.getMonth()]
  const year = date.getFullYear()
  
  // Check if it's today or tomorrow
  if (date.toDateString() === today.toDateString()) {
    return { display: `Today, ${day} ${month}`, isToday: true, isTomorrow: false }
  } else if (date.toDateString() === tomorrow.toDateString()) {
    return { display: `Tomorrow, ${day} ${month}`, isToday: false, isTomorrow: true }
  } else {
    return { display: `${dayName}, ${day} ${month} ${year}`, isToday: false, isTomorrow: false }
  }
}

const getTimeFromDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: false })
}

const getDaysUntil = (dateString: string) => {
  const eventDate = new Date(dateString)
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  eventDate.setHours(0, 0, 0, 0)
  
  const diffTime = eventDate.getTime() - today.getTime()
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  
  return diffDays
}

export default function UpcomingEvents() {
  const [currentTime, setCurrentTime] = useState(new Date())
  const [events, setEvents] = useState<Event[]>([])
  const [isLoading, setIsLoading] = useState(true)

  useEffect(() => {
    const timer = setInterval(() => {
      setCurrentTime(new Date())
    }, 1000)

    return () => clearInterval(timer)
  }, [])

  useEffect(() => {
    const fetchUpcomingEvents = async () => {
      try {
        const upcoming = await eventsApi.getUpcoming(6)
        setEvents(upcoming)
      } catch (error) {
        console.error('Error fetching upcoming events:', error)
        setEvents([])
      } finally {
        setIsLoading(false)
      }
    }

    fetchUpcomingEvents()
  }, [])

  // Filter and sort events (only future events)
  const upcomingEvents = events
    .filter(event => {
      const eventDate = new Date(event.startDate)
      return eventDate > currentTime
    })
    .sort((a, b) => {
      const dateA = new Date(a.startDate)
      const dateB = new Date(b.startDate)
      return dateA.getTime() - dateB.getTime()
    })
    .slice(0, 6) // Show up to 6 events

  return (
    <section className="py-8 px-4">
      <div className="max-w-6xl mx-auto">
        {/* Header */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ duration: 0.6 }}
          className="mb-8"
        >
          <div className="flex items-center gap-3 mb-4">
            <div className="relative">
              <Calendar className="w-8 h-8 text-primary-light" />
              <motion.div
                animate={{ scale: [1, 1.2, 1], opacity: [0.5, 1, 0.5] }}
                transition={{ duration: 2, repeat: Infinity }}
                className="absolute -top-1 -right-1"
              >
                <Sparkles className="w-4 h-4 text-primary-light" />
              </motion.div>
            </div>
            <h2 className="text-3xl md:text-4xl font-bold text-white">
              Upcoming Events
            </h2>
          </div>
          <p className="text-white/70 text-lg">
            Join us for community meetings, public hearings, and cultural celebrations
          </p>
        </motion.div>

        {/* Events Grid */}
        {isLoading ? (
          <div className="text-center py-12">
            <div className="text-white/70">Loading upcoming events...</div>
          </div>
        ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {upcomingEvents.map((event, index) => {
              const dateInfo = formatDate(event.startDate)
              const daysUntil = getDaysUntil(event.startDate)
              const time = getTimeFromDate(event.startDate)
              const categoryColor = categoryColors[event.category] || categoryColors.General
            
            return (
              <motion.div
                  key={event._id}
                initial={{ opacity: 0, y: 30 }}
                whileInView={{ opacity: 1, y: 0 }}
                viewport={{ once: true }}
                transition={{ duration: 0.5, delay: index * 0.1 }}
                whileHover={{ y: -8, scale: 1.02 }}
                className="relative group"
              >
                <div className="glass rounded-xl p-6 shadow-xl glass-hover h-full flex flex-col border-2 border-white/10 hover:border-primary/30 transition-all duration-300">
                  {/* Days Until Badge */}
                  {daysUntil >= 0 && daysUntil <= 7 && (
                    <div className="absolute -top-2 -left-2 bg-gradient-primary text-white px-3 py-1 rounded-full text-xs font-bold shadow-lg z-10">
                      {daysUntil === 0 ? 'TODAY' : daysUntil === 1 ? 'TOMORROW' : `${daysUntil} DAYS`}
                    </div>
                  )}

                  {/* Category Badge */}
                  <div className="mb-4">
                      <span className={`inline-block px-3 py-1 rounded-full text-xs font-semibold border ${categoryColor}`}>
                      {event.category}
                    </span>
                  </div>

                  {/* Date & Time */}
                  <div className="mb-4 space-y-2">
                    <div className="flex items-center gap-2 text-white/90">
                      <Calendar className="w-4 h-4 text-primary-light" />
                      <span className={`font-semibold ${dateInfo.isToday ? 'text-primary-light' : dateInfo.isTomorrow ? 'text-secondary-light' : ''}`}>
                        {dateInfo.display}
                      </span>
                    </div>
                    <div className="flex items-center gap-2 text-white/70">
                      <Clock className="w-4 h-4 text-primary-light" />
                        <span>{time}</span>
                    </div>
                    <div className="flex items-center gap-2 text-white/70">
                      <MapPin className="w-4 h-4 text-primary-light" />
                      <span className="text-sm">{event.location}</span>
                    </div>
                  </div>

                  {/* Title */}
                  <h3 className="text-xl font-bold text-white mb-3 group-hover:text-primary-light transition-colors line-clamp-2">
                    {event.title}
                  </h3>

                  {/* Description */}
                  <p className="text-white/70 text-sm mb-4 flex-grow line-clamp-3">
                    {event.description}
                  </p>

                  {/* Footer */}
                  <div className="flex items-center justify-between pt-4 border-t border-white/10">
                      {event.link ? (
                        <a
                          href={event.link}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="flex items-center gap-1 text-primary-light font-semibold text-sm hover:text-primary transition-colors"
                        >
                          Details <ArrowRight className="w-4 h-4" />
                        </a>
                      ) : (
                    <motion.button
                      whileHover={{ x: 5 }}
                      className="flex items-center gap-1 text-primary-light font-semibold text-sm hover:text-primary transition-colors"
                    >
                      Details <ArrowRight className="w-4 h-4" />
                    </motion.button>
                      )}
                  </div>
                </div>
              </motion.div>
            )
          })}
        </div>
        )}

        {/* View All Events Link */}
        {upcomingEvents.length > 0 && (
          <motion.div
            initial={{ opacity: 0 }}
            whileInView={{ opacity: 1 }}
            viewport={{ once: true }}
            transition={{ duration: 0.6, delay: 0.4 }}
            className="text-center mt-8"
          >
            <Link href="/events">
              <motion.button
                whileHover={{ scale: 1.05 }}
                whileTap={{ scale: 0.95 }}
                className="px-6 py-3 glass rounded-full text-white font-semibold hover:bg-white/20 transition-all flex items-center gap-2 mx-auto"
              >
                View All Events
                <Calendar className="w-4 h-4" />
              </motion.button>
            </Link>
          </motion.div>
        )}

        {/* Empty State */}
        {upcomingEvents.length === 0 && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            className="text-center py-12"
          >
            <Calendar className="w-16 h-16 text-white/30 mx-auto mb-4" />
            <p className="text-white/60 text-lg">No upcoming events scheduled</p>
            <p className="text-white/40 text-sm mt-2">Check back soon for new events</p>
          </motion.div>
        )}
      </div>
    </section>
  )
}
