'use client';

import { useState, useEffect } from 'react';
import type { ArtEvent } from '@/lib/types';

export default function AdminEvents() {
  const [events, setEvents] = useState<ArtEvent[]>([]);
  const [editing, setEditing] = useState<ArtEvent | null>(null);
  const [isNew, setIsNew] = useState(false);
  const [loading, setLoading] = useState(true);

  const fetchEvents = async () => {
    const res = await fetch('/api/admin/events');
    setEvents(await res.json());
    setLoading(false);
  };

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

  const handleSave = async () => {
    if (!editing) return;
    const method = isNew ? 'POST' : 'PUT';
    const url = isNew ? '/api/admin/events' : `/api/admin/events/${editing.id}`;
    await fetch(url, {
      method,
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(editing),
    });
    setEditing(null);
    setIsNew(false);
    fetchEvents();
  };

  const handleDelete = async (id: string) => {
    if (!confirm('Delete this event?')) return;
    await fetch(`/api/admin/events/${id}`, { method: 'DELETE' });
    fetchEvents();
  };

  const handleUpload = async (file: File): Promise<string> => {
    const form = new FormData();
    form.append('file', file);
    const res = await fetch('/api/admin/upload', { method: 'POST', body: form });
    const data = await res.json();
    return data.url || '';
  };

  const newEvent = (): ArtEvent => ({
    id: `event-${Date.now()}`,
    title: '',
    description: '',
    image: '',
    date: '',
    link: '',
    section: 'reevolution',
    sortOrder: events.length + 1,
  });

  if (loading) return <div className="p-8 text-gray-400">Loading...</div>;

  const reevolutionEvents = events.filter(e => e.section === 'reevolution').sort((a, b) => a.sortOrder - b.sortOrder);
  const xhivaEvents = events.filter(e => e.section === 'xhiva').sort((a, b) => a.sortOrder - b.sortOrder);

  return (
    <div className="p-8">
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-light">Events</h1>
        <button
          onClick={() => { setEditing(newEvent()); setIsNew(true); }}
          className="px-4 py-2 bg-[#2d2d2d] text-white rounded-lg text-sm hover:bg-[#c9a962] transition-colors"
        >
          + Add Event
        </button>
      </div>

      {/* Edit Modal */}
      {editing && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl max-w-lg w-full max-h-[90vh] overflow-y-auto p-6">
            <h2 className="text-xl font-light mb-4">{isNew ? 'New Event' : 'Edit Event'}</h2>
            <div className="space-y-4">
              <div>
                <label className="block text-xs tracking-widest mb-1">TITLE</label>
                <input value={editing.title} onChange={(e) => setEditing({...editing, title: e.target.value})}
                  className="w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:border-[#c9a962]" />
              </div>
              <div>
                <label className="block text-xs tracking-widest mb-1">DESCRIPTION</label>
                <textarea value={editing.description} onChange={(e) => setEditing({...editing, description: e.target.value})} rows={3}
                  className="w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:border-[#c9a962] resize-none" />
              </div>
              <div>
                <label className="block text-xs tracking-widest mb-1">IMAGE</label>
                {editing.image && (
                  <div className="w-20 h-14 bg-gray-100 rounded overflow-hidden mb-2">
                    <img src={editing.image} alt="" className="w-full h-full object-cover" />
                  </div>
                )}
                <label className="text-xs text-blue-600 hover:text-blue-800 cursor-pointer block mb-2">
                  Upload image
                  <input type="file" accept="image/*" className="hidden" onChange={async (e) => {
                    const file = e.target.files?.[0];
                    if (file) { const url = await handleUpload(file); if (url) setEditing({...editing, image: url}); }
                  }} />
                </label>
                <input value={editing.image} onChange={(e) => setEditing({...editing, image: e.target.value})}
                  className="w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:border-[#c9a962]"
                  placeholder="Or paste image path" />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs tracking-widest mb-1">DATE</label>
                  <input value={editing.date} onChange={(e) => setEditing({...editing, date: e.target.value})}
                    className="w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:border-[#c9a962]"
                    placeholder="e.g. March 2026" />
                </div>
                <div>
                  <label className="block text-xs tracking-widest mb-1">SECTION</label>
                  <select value={editing.section} onChange={(e) => setEditing({...editing, section: e.target.value as 'xhiva' | 'reevolution'})}
                    className="w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:border-[#c9a962]">
                    <option value="reevolution">Re Evolution Art</option>
                    <option value="xhiva">XHIVA</option>
                  </select>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs tracking-widest mb-1">LINK</label>
                  <input value={editing.link} onChange={(e) => setEditing({...editing, link: e.target.value})}
                    className="w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:border-[#c9a962]"
                    placeholder="https://..." />
                </div>
                <div>
                  <label className="block text-xs tracking-widest mb-1">SORT ORDER</label>
                  <input type="number" value={editing.sortOrder} onChange={(e) => setEditing({...editing, sortOrder: parseInt(e.target.value) || 0})}
                    className="w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:border-[#c9a962]" />
                </div>
              </div>
            </div>
            <div className="flex gap-3 mt-6">
              <button onClick={handleSave} className="px-6 py-2 bg-[#2d2d2d] text-white rounded-lg text-sm hover:bg-[#c9a962] transition-colors">
                Save
              </button>
              <button onClick={() => { setEditing(null); setIsNew(false); }} className="px-6 py-2 border rounded-lg text-sm hover:bg-gray-50">
                Cancel
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Event List by section */}
      {reevolutionEvents.length > 0 && (
        <div className="mb-8">
          <h2 className="text-sm tracking-widest text-gray-500 mb-3">RE EVOLUTION ART</h2>
          <div className="bg-white rounded-xl shadow-sm overflow-hidden">
            <EventTable events={reevolutionEvents} onEdit={(e) => { setEditing(e); setIsNew(false); }} onDelete={handleDelete} />
          </div>
        </div>
      )}

      {xhivaEvents.length > 0 && (
        <div>
          <h2 className="text-sm tracking-widest text-gray-500 mb-3">XHIVA</h2>
          <div className="bg-white rounded-xl shadow-sm overflow-hidden">
            <EventTable events={xhivaEvents} onEdit={(e) => { setEditing(e); setIsNew(false); }} onDelete={handleDelete} />
          </div>
        </div>
      )}
    </div>
  );
}

function EventTable({ events, onEdit, onDelete }: { events: ArtEvent[]; onEdit: (e: ArtEvent) => void; onDelete: (id: string) => void }) {
  return (
    <table className="w-full text-sm">
      <thead className="bg-gray-50 text-left">
        <tr>
          <th className="px-4 py-3 text-xs tracking-widest text-gray-500">IMAGE</th>
          <th className="px-4 py-3 text-xs tracking-widest text-gray-500">TITLE</th>
          <th className="px-4 py-3 text-xs tracking-widest text-gray-500">DATE</th>
          <th className="px-4 py-3 text-xs tracking-widest text-gray-500">ACTIONS</th>
        </tr>
      </thead>
      <tbody className="divide-y">
        {events.map((event) => (
          <tr key={event.id} className="hover:bg-gray-50">
            <td className="px-4 py-3">
              {event.image && (
                <div className="w-16 h-10 rounded overflow-hidden bg-gray-100">
                  <img src={event.image} alt="" className="w-full h-full object-cover" />
                </div>
              )}
            </td>
            <td className="px-4 py-3 font-medium">{event.title}</td>
            <td className="px-4 py-3 text-gray-500">{event.date || '—'}</td>
            <td className="px-4 py-3">
              <button onClick={() => onEdit(event)} className="text-blue-600 hover:text-blue-800 mr-3 text-xs">Edit</button>
              <button onClick={() => onDelete(event.id)} className="text-red-600 hover:text-red-800 text-xs">Delete</button>
            </td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}
