import React, { useEffect, useState } from 'react';
import api from '../../utils/api';
import { Card } from '../../components/ui/card';
import { Button } from '../../components/ui/button';
import { Badge } from '../../components/ui/badge';
import { Input } from '../../components/ui/input';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '../../components/ui/dialog';
import { toast } from 'sonner';
import { Calendar, MapPin, Users, Plus, Edit, Trash2, Eye, EyeOff } from 'lucide-react';
import { AttendanceDialog } from '../../components/AttendanceDialog';

const AdminEvents = () => {
  const [events, setEvents] = useState([]);
  const [loading, setLoading] = useState(true);
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
  const [editingEvent, setEditingEvent] = useState(null);
  const [attendanceDialogOpen, setAttendanceDialogOpen] = useState(false);
  const [selectedEvent, setSelectedEvent] = useState(null);

  const [formData, setFormData] = useState({
    title: '',
    description: '',
    start_at: '',
    end_at: '',
    location: '',
    capacity: '',
    published: false
  });

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

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

  const handleSubmit = async (e) => {
    e.preventDefault();

    try {
      const eventData = {
        ...formData,
        capacity: formData.capacity ? parseInt(formData.capacity) : null,
        start_at: new Date(formData.start_at).toISOString(),
        end_at: new Date(formData.end_at).toISOString()
      };

      if (editingEvent) {
        await api.put(`/admin/events/${editingEvent.id}`, eventData);
        toast.success('Event updated successfully');
      } else {
        await api.post('/admin/events', eventData);
        toast.success('Event created successfully');
      }

      setIsCreateDialogOpen(false);
      setEditingEvent(null);
      resetForm();
      fetchEvents();
    } catch (error) {
      toast.error(error.response?.data?.detail || 'Failed to save event');
    }
  };

  const handleEdit = (event) => {
    setEditingEvent(event);
    setFormData({
      title: event.title,
      description: event.description || '',
      start_at: new Date(event.start_at).toISOString().slice(0, 16),
      end_at: new Date(event.end_at).toISOString().slice(0, 16),
      location: event.location,
      capacity: event.capacity || '',
      published: event.published
    });
    setIsCreateDialogOpen(true);
  };

  const handleDelete = async (eventId) => {
    if (!window.confirm('Are you sure you want to delete this event?')) {
      return;
    }

    try {
      await api.delete(`/admin/events/${eventId}`);
      toast.success('Event deleted successfully');
      fetchEvents();
    } catch (error) {
      toast.error('Failed to delete event');
    }
  };

  const togglePublish = async (event) => {
    try {
      await api.put(`/admin/events/${event.id}`, {
        published: !event.published
      });
      toast.success(event.published ? 'Event unpublished' : 'Event published');
      fetchEvents();
    } catch (error) {
      toast.error('Failed to update event');
    }
  };

  const resetForm = () => {
    setFormData({
      title: '',
      description: '',
      start_at: '',
      end_at: '',
      location: '',
      capacity: '',
      published: false
    });
  };

  const handleDialogClose = () => {
    setIsCreateDialogOpen(false);
    setEditingEvent(null);
    resetForm();
  };

  return (
    <>
      {/* Header */}
      <div className="mb-8 flex flex-col sm:flex-row gap-4 justify-between items-start sm:items-center">
        <div>
          <h1 className="text-4xl md:text-5xl font-semibold text-[#422268] mb-4" style={{ fontFamily: "'Inter', sans-serif" }}>
            Event Management
          </h1>
          <p className="text-lg text-[#664fa3]" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
            Create and manage community events.
          </p>
        </div>

          <Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
            <DialogTrigger asChild>
              <Button
                onClick={() => {
                  resetForm();
                  setEditingEvent(null);
                }}
                className="bg-[#DDD8EB] text-[#422268] hover:bg-white rounded-full px-6"
                data-testid="create-event-button"
              >
                <Plus className="mr-2 h-5 w-5" />
                Create Event
              </Button>
            </DialogTrigger>

            <DialogContent className="max-w-[calc(100vw-2rem)] sm:max-w-2xl max-h-[90vh] overflow-y-auto">
              <DialogHeader>
                <DialogTitle className="text-2xl text-[#422268]" style={{ fontFamily: "'Inter', sans-serif" }}>
                  {editingEvent ? 'Edit Event' : 'Create New Event'}
                </DialogTitle>
              </DialogHeader>

              <form onSubmit={handleSubmit} className="space-y-4 mt-4">
                <div>
                  <label className="block text-sm font-medium text-[#422268] mb-2" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                    Title *
                  </label>
                  <Input
                    value={formData.title}
                    onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                    required
                    className="border-2 border-[#ddd8eb] focus:border-[#664fa3]"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-[#422268] mb-2" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                    Description
                  </label>
                  <textarea
                    value={formData.description}
                    onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                    rows={4}
                    className="w-full border-2 border-[#ddd8eb] focus:border-[#664fa3] rounded-lg p-3"
                  />
                </div>

                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-[#422268] mb-2" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                      Start Date & Time *
                    </label>
                    <Input
                      type="datetime-local"
                      value={formData.start_at}
                      onChange={(e) => setFormData({ ...formData, start_at: e.target.value })}
                      required
                      className="border-2 border-[#ddd8eb] focus:border-[#664fa3]"
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-[#422268] mb-2" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                      End Date & Time *
                    </label>
                    <Input
                      type="datetime-local"
                      value={formData.end_at}
                      onChange={(e) => setFormData({ ...formData, end_at: e.target.value })}
                      required
                      className="border-2 border-[#ddd8eb] focus:border-[#664fa3]"
                    />
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-[#422268] mb-2" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                    Location *
                  </label>
                  <Input
                    value={formData.location}
                    onChange={(e) => setFormData({ ...formData, location: e.target.value })}
                    required
                    className="border-2 border-[#ddd8eb] focus:border-[#664fa3]"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-[#422268] mb-2" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                    Capacity (optional)
                  </label>
                  <Input
                    type="number"
                    value={formData.capacity}
                    onChange={(e) => setFormData({ ...formData, capacity: e.target.value })}
                    placeholder="Leave empty for unlimited"
                    className="border-2 border-[#ddd8eb] focus:border-[#664fa3]"
                  />
                </div>

                <div className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    id="published"
                    checked={formData.published}
                    onChange={(e) => setFormData({ ...formData, published: e.target.checked })}
                    className="w-4 h-4 text-[#664fa3] border-[#ddd8eb] rounded focus:ring-[#664fa3]"
                  />
                  <label htmlFor="published" className="text-sm font-medium text-[#422268]" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                    Publish event (make visible to members)
                  </label>
                </div>

                <div className="flex flex-col-reverse sm:flex-row gap-3 pt-4">
                  <Button
                    type="button"
                    variant="outline"
                    onClick={handleDialogClose}
                    className="flex-1 border-2 border-gray-400 text-gray-600 hover:bg-gray-400 hover:text-white rounded-full"
                  >
                    Cancel
                  </Button>
                  <Button
                    type="submit"
                    className="flex-1 bg-[#DDD8EB] text-[#422268] hover:bg-white rounded-full"
                  >
                    {editingEvent ? 'Update Event' : 'Create Event'}
                  </Button>
                </div>
              </form>
            </DialogContent>
          </Dialog>
        </div>

        {/* Events List */}
        {loading ? (
          <div className="text-center py-20">
            <p className="text-[#664fa3]" 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">
            {events.map((event) => (
              <Card
                key={event.id}
                className="p-6 bg-white rounded-2xl border border-[#ddd8eb] hover:shadow-lg transition-all"
                data-testid={`event-card-${event.id}`}
              >
                {/* Event Header */}
                <div className="flex justify-between items-start mb-4">
                  <div className="bg-[#DDD8EB]/20 p-3 rounded-lg">
                    <Calendar className="h-6 w-6 text-[#664fa3]" />
                  </div>
                  <Badge
                    className={`${
                      event.published
                        ? 'bg-[#81B29A] text-white'
                        : 'bg-gray-400 text-white'
                    } px-3 py-1 rounded-full`}
                  >
                    {event.published ? 'Published' : 'Draft'}
                  </Badge>
                </div>

                {/* Event Details */}
                <h3 className="text-xl font-semibold text-[#422268] mb-3" style={{ fontFamily: "'Inter', sans-serif" }}>
                  {event.title}
                </h3>

                {event.description && (
                  <p className="text-[#664fa3] mb-4 line-clamp-2 text-sm" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                    {event.description}
                  </p>
                )}

                <div className="space-y-2 mb-4">
                  <div className="flex items-center gap-2 text-sm text-[#664fa3]" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                    <Calendar className="h-4 w-4" />
                    <span>
                      {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-sm text-[#664fa3]" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                    <MapPin className="h-4 w-4" />
                    <span className="truncate">{event.location}</span>
                  </div>
                  <div className="flex items-center gap-2 text-sm text-[#664fa3]" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                    <Users className="h-4 w-4" />
                    <span>{event.rsvp_count || 0} attending</span>
                  </div>
                </div>

                {/* Actions */}
                <div className="space-y-2 pt-4 border-t border-[#ddd8eb]">
                  {/* Mark Attendance Button */}
                  <Button
                    onClick={() => {
                      setSelectedEvent(event);
                      setAttendanceDialogOpen(true);
                    }}
                    variant="outline"
                    size="sm"
                    className="w-full border-[#81B29A] text-[#81B29A] hover:bg-[#81B29A] hover:text-white"
                    data-testid={`mark-attendance-${event.id}`}
                  >
                    <Users className="h-4 w-4 mr-2" />
                    Mark Attendance ({event.rsvp_count || 0} RSVPs)
                  </Button>

                  {/* Other Actions */}
                  <div className="flex gap-2">
                    <Button
                      onClick={() => togglePublish(event)}
                      variant="outline"
                      size="sm"
                      className="flex-1 border-[#664fa3] text-[#664fa3] hover:bg-[#664fa3] hover:text-white"
                      data-testid={`toggle-publish-${event.id}`}
                    >
                      {event.published ? (
                        <>
                          <EyeOff className="h-4 w-4 mr-1" />
                          Unpublish
                        </>
                      ) : (
                        <>
                          <Eye className="h-4 w-4 mr-1" />
                          Publish
                        </>
                      )}
                    </Button>
                    <Button
                      onClick={() => handleEdit(event)}
                      variant="outline"
                      size="sm"
                      className="border-gray-400 text-gray-600 hover:bg-gray-400 hover:text-white"
                      data-testid={`edit-event-${event.id}`}
                    >
                      <Edit className="h-4 w-4" />
                    </Button>
                    <Button
                      onClick={() => handleDelete(event.id)}
                      variant="outline"
                      size="sm"
                      className="border-red-500 text-red-500 hover:bg-red-500 hover:text-white"
                      data-testid={`delete-event-${event.id}`}
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              </Card>
            ))}
          </div>
        ) : (
          <div className="text-center py-20">
            <Calendar className="h-20 w-20 text-[#ddd8eb] mx-auto mb-6" />
            <h3 className="text-2xl font-semibold text-[#422268] mb-4" style={{ fontFamily: "'Inter', sans-serif" }}>
              No Events Yet
            </h3>
            <p className="text-[#664fa3] mb-6" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
              Create your first event to get started!
            </p>
            <Button
              onClick={() => setIsCreateDialogOpen(true)}
              className="bg-[#DDD8EB] text-[#422268] hover:bg-white rounded-full px-8"
            >
              <Plus className="mr-2 h-5 w-5" />
              Create Event
            </Button>
          </div>
        )}

      {/* Attendance Dialog */}
      <AttendanceDialog
        event={selectedEvent}
        open={attendanceDialogOpen}
        onOpenChange={setAttendanceDialogOpen}
        onSuccess={fetchEvents}
      />
    </>
  );
};

export default AdminEvents;
