import React, { useState } from 'react'
import { Link } from 'react-router-dom'
import { deleteEvent, getAdminToken } from '../../utils/api'
import { useEvents } from '../../hooks/useEvents'

export default function AdminEvents() {
  const { events, loading, error, reload } = useEvents()
  const [busySlug, setBusySlug] = useState('')
  const [feedback, setFeedback] = useState('')

  const handleDelete = async (slug) => {
    if (!window.confirm('Delete this event? This action cannot be undone.')) {
      return
    }

    const token = getAdminToken()
    if (!token) {
      setFeedback('No admin token found. Please log in again.')
      return
    }

    setBusySlug(slug)
    setFeedback('')
    try {
      await deleteEvent(slug, token)
      await reload()
      setFeedback('Event deleted successfully.')
    } catch (err) {
      console.error('Failed to delete event', err)
      setFeedback(err.message || 'Unable to delete event. Please try again.')
    } finally {
      setBusySlug('')
    }
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between gap-4">
        <div>
          <h1 className="text-3xl font-semibold text-slate-900 mb-1">Manage Events</h1>
          <p className="text-muted">Create, edit, and remove upcoming events.</p>
        </div>
        <Link to="/admin/events/new" className="btn">
          Add Event
        </Link>
      </div>

      {feedback && <div className="bg-sand border border-subtle rounded-md px-4 py-3 text-sm">{feedback}</div>}

      {loading && <p className="text-muted">Loading events...</p>}
      {error && !loading && <p className="text-red-600">Unable to load events. Please refresh.</p>}

      {!loading && !error && (
        <div className="overflow-x-auto bg-white border border-subtle rounded-xl shadow-sm">
          <table className="min-w-full divide-y divide-subtle">
            <thead className="bg-slate-50">
              <tr>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-600 uppercase tracking-wide">Title</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-600 uppercase tracking-wide">Date</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-600 uppercase tracking-wide">Time</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-600 uppercase tracking-wide">Location</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-600 uppercase tracking-wide">Slug</th>
                <th className="px-4 py-3 text-right text-xs font-semibold text-slate-600 uppercase tracking-wide">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-subtle">
              {events.length === 0 && (
                <tr>
                  <td colSpan={6} className="px-4 py-6 text-center text-muted">
                    No events yet. Click "Add Event" to create the first one.
                  </td>
                </tr>
              )}
              {events.map(event => (
                <tr key={event.slug} className="hover:bg-slate-50">
                  <td className="px-4 py-3 text-sm font-medium text-slate-900">{event.title}</td>
                  <td className="px-4 py-3 text-sm text-slate-600">{event.date}</td>
                  <td className="px-4 py-3 text-sm text-slate-600">{event.time}</td>
                  <td className="px-4 py-3 text-sm text-slate-600">{event.location}</td>
                  <td className="px-4 py-3 text-sm text-slate-600">{event.slug}</td>
                  <td className="px-4 py-3 text-sm text-right flex justify-end gap-2">
                    <Link to={`/admin/events/${event.slug}/edit`} className="btn-outline text-sm">
                      Edit
                    </Link>
                    <button
                      type="button"
                      className="btn-outline text-sm text-red-600 border-red-200 hover:bg-red-50"
                      onClick={() => handleDelete(event.slug)}
                      disabled={busySlug === event.slug}
                    >
                      {busySlug === event.slug ? 'Deleting...' : 'Delete'}
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  )
}
