"use client" import { useState, useEffect } from "react" import { Button } from "@/components/ui/button" import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" import { Input } from "@/components/ui/input" import { Label } from "@/components/ui/label" import { Textarea } from "@/components/ui/textarea" import { Badge } from "@/components/ui/badge" import { Switch } from "@/components/ui/switch" import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog" import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from "@/components/ui/alert-dialog" import { Plus, Edit, Trash2, Users, Calendar, Clock, Play, StopCircle, Eye, ArrowLeft } from "lucide-react" import Link from "next/link" import { AuthGuard } from "@/components/auth-guard" import { useAuth } from "@/hooks/use-auth" import apiClient from "@/lib/api-client" import { API_CONFIG } from "@/lib/config" import { useToast } from "@/hooks/use-toast" interface VoteEvent { id: string title: string description: string start_date: string end_date: string is_active: boolean is_voting_open: boolean created_at: string updated_at: string candidates?: Candidate[] } interface Candidate { id: string vote_event_id: string name: string image_url: string description: string created_at: string updated_at: string } interface EventFormData { title: string description: string start_date: string end_date: string is_active: boolean results_open: boolean } function EventManagementContent() { const { user, logout } = useAuth() const { toast } = useToast() const [events, setEvents] = useState([]) const [loading, setLoading] = useState(true) const [formData, setFormData] = useState({ title: "", description: "", start_date: "", end_date: "", is_active: true, results_open: false }) const [editingEvent, setEditingEvent] = useState(null) const [isDialogOpen, setIsDialogOpen] = useState(false) const [submitting, setSubmitting] = useState(false) useEffect(() => { fetchEvents() }, []) const fetchEvents = async () => { try { setLoading(true) const response = await apiClient.get(API_CONFIG.ENDPOINTS.VOTE_EVENTS) if (response.data.success) { setEvents(response.data.data.vote_events || []) } } catch (error) { console.error('Error fetching events:', error) toast({ title: "Error", description: "Failed to fetch vote events", variant: "destructive" }) } finally { setLoading(false) } } const handleSubmit = async (e: React.FormEvent) => { e.preventDefault() setSubmitting(true) try { if (editingEvent) { // Update existing event - includes is_active field const updatePayload = { title: formData.title, description: formData.description, start_date: new Date(formData.start_date).toISOString(), end_date: new Date(formData.end_date).toISOString(), is_active: formData.is_active, results_open: formData.results_open } await apiClient.put(`${API_CONFIG.ENDPOINTS.VOTE_EVENTS}/${editingEvent.id}`, updatePayload) toast({ title: "Success", description: "Event updated successfully" }) } else { // Create new event - different payload structure (no is_active field) const createPayload = { title: formData.title, description: formData.description, start_date: new Date(formData.start_date).toISOString(), end_date: new Date(formData.end_date).toISOString(), results_open: formData.results_open } await apiClient.post(API_CONFIG.ENDPOINTS.VOTE_EVENTS, createPayload) toast({ title: "Success", description: "Event created successfully" }) } setIsDialogOpen(false) resetForm() fetchEvents() } catch (error) { console.error('Error saving event:', error) toast({ title: "Error", description: editingEvent ? "Failed to update event" : "Failed to create event", variant: "destructive" }) } finally { setSubmitting(false) } } const handleEdit = (event: VoteEvent) => { setEditingEvent(event) setFormData({ title: event.title, description: event.description, start_date: new Date(event.start_date).toISOString().slice(0, 16), end_date: new Date(event.end_date).toISOString().slice(0, 16), is_active: event.is_active, results_open: false // Default to false since this field might not exist in the current event object }) setIsDialogOpen(true) } const handleDelete = async (eventId: string) => { try { await apiClient.delete(`${API_CONFIG.ENDPOINTS.VOTE_EVENTS}/${eventId}`) toast({ title: "Success", description: "Event deleted successfully" }) fetchEvents() } catch (error) { console.error('Error deleting event:', error) toast({ title: "Error", description: "Failed to delete event", variant: "destructive" }) } } const resetForm = () => { setFormData({ title: "", description: "", start_date: "", end_date: "", is_active: true, results_open: false }) setEditingEvent(null) } const getEventStatus = (event: VoteEvent) => { const now = new Date() const start = new Date(event.start_date) const end = new Date(event.end_date) if (now < start) return "upcoming" if (now >= start && now <= end) return "active" return "ended" } const getStatusBadge = (event: VoteEvent) => { const status = getEventStatus(event) if (event.is_voting_open && status === "active") { return ( Live Voting ) } switch (status) { case "active": return ( Active ) case "upcoming": return ( Upcoming ) case "ended": return ( Ended ) } } return (
METI - New & Renewable Energy

Event Management

Welcome, {user?.username || 'Admin'}
{/* Header with Create Button */}

Vote Events

Manage voting events and candidates

{editingEvent ? 'Edit Event' : 'Create New Event'} {editingEvent ? 'Update the event details below.' : 'Fill in the details to create a new voting event.'}
setFormData({ ...formData, title: e.target.value })} placeholder="Enter event title" required />