import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import api from '../utils/api';
import { Card } from '../components/ui/card';
import { Badge } from '../components/ui/badge';
import Navbar from '../components/Navbar';
import MemberFooter from '../components/MemberFooter';
import { Calendar, MapPin, Users, ArrowRight } from 'lucide-react';

const Events = () => {
  const [events, setEvents] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchEvents();
  }, []);

  const fetchEvents = async () => {
    try {
      const response = await api.get('/events');
      setEvents(response.data);
    } catch (error) {
      console.error('Failed to fetch events:', error);
    } finally {
      setLoading(false);
    }
  };

  const getRSVPBadge = (rsvpStatus) => {
    if (!rsvpStatus) return null;

    const config = {
      yes: { label: 'Going', className: 'bg-[var(--green-light)] text-white' },
      no: { label: 'Not Going', className: 'bg-gray-400 text-white' },
      maybe: { label: 'Maybe', className: 'bg-orange-100 text-orange-700' }
    };

    const rsvpConfig = config[rsvpStatus];
    if (!rsvpConfig) return null;

    return (
      <Badge className={`${rsvpConfig.className} px-3 py-1 rounded-full text-sm`}>
        {rsvpConfig.label}
      </Badge>
    );
  };

  return (
    <div className="min-h-screen bg-gradient-to-b from-[var(--neutral-100)] to-[var(--neutral-800)]">
      <Navbar />

      <div className="max-w-7xl mx-auto px-6 py-12">
        <div className="mb-12">
          <h1 className="text-4xl md:text-5xl font-semibold text-[var(--purple-ink)] mb-4" style={{ fontFamily: "'Inter', sans-serif" }}>
            Upcoming Events
          </h1>
          <p className="text-lg text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
            Browse and RSVP to our community events.
          </p>
        </div>

        {loading ? (
          <div className="text-center py-20">
            <p className="text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>Loading events...</p>
          </div>
        ) : events.length > 0 ? (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6 sm:gap-8">
            {events.map((event) => (
              <Link to={`/events/${event.id}`} key={event.id}>
                <Card
                  className="p-6 bg-background rounded-2xl border border-[var(--neutral-800)] hover:shadow-lg hover:-translate-y-1 transition-all cursor-pointer h-full"
                  data-testid={`event-card-${event.id}`}
                >
                  <div className="flex justify-between items-start mb-4">
                    <div className="bg-[var(--neutral-800)]/20 p-3 rounded-lg">
                      <Calendar className="h-6 w-6 text-brand-purple " />
                    </div>
                    {getRSVPBadge(event.user_rsvp_status)}
                  </div>

                  <h3 className="text-xl font-semibold text-[var(--purple-ink)] mb-3" style={{ fontFamily: "'Inter', sans-serif" }}>
                    {event.title}
                  </h3>

                  {event.description && (
                    <p className="text-brand-purple  mb-4 line-clamp-2" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                      {event.description}
                    </p>
                  )}

                  <div className="space-y-2 text-sm">
                    <div className="flex items-center gap-2 text-brand-purple ">
                      <Calendar className="h-4 w-4" />
                      <span style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                        {new Date(event.start_at).toLocaleDateString()} at{' '}
                        {new Date(event.start_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                      </span>
                    </div>
                    <div className="flex items-center gap-2 text-brand-purple ">
                      <MapPin className="h-4 w-4" />
                      <span style={{ fontFamily: "'Nunito Sans', sans-serif" }}>{event.location}</span>
                    </div>
                    <div className="flex items-center gap-2 text-brand-purple ">
                      <Users className="h-4 w-4" />
                      <span style={{ fontFamily: "'Nunito Sans', sans-serif" }}>{event.rsvp_count || 0} attending</span>
                    </div>
                  </div>

                  <div className="mt-6 flex items-center text-[var(--orange-light)] font-medium">
                    View Details
                    <ArrowRight className="ml-2 h-4 w-4" />
                  </div>
                </Card>
              </Link>
            ))}
          </div>
        ) : (
          <div className="text-center py-20">
            <Calendar className="h-20 w-20 text-[var(--neutral-800)] mx-auto mb-6" />
            <h3 className="text-2xl font-semibold text-[var(--purple-ink)] mb-4" style={{ fontFamily: "'Inter', sans-serif" }}>
              No Events Available
            </h3>
            <p className="text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
              There are no upcoming events at the moment. Check back later!
            </p>
          </div>
        )}
      </div>
      <MemberFooter />
    </div>
  );
};

export default Events;
