'use client';
import React, { useState, useEffect } from 'react';
import { Calendar, Plus, Save, X, Loader2, Pencil, Trash2 } from 'lucide-react';
import ImageUpload from '@/components/admin/ImageUpload';
import RichTextEditor from '@/components/admin/RichTextEditor';

export default function AdminEvents() {
  const [isCreating, setIsCreating] = useState(false);
  const [events, setEvents] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [formData, setFormData] = useState({
    title: '',
    subtitle: '',
    startDate: '',
    timeText: '',
    locationText: '',
    detailsContent: '', // Rich Text
    posterImage: '',
    galleryImages: [] as string[]
  });
  const [submitting, setSubmitting] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [pastPage, setPastPage] = useState(1);
  const [todayTs, setTodayTs] = useState<number | null>(null);
  const pageSize = 8;

  const filteredEvents = events.filter((event: any) => {
    const term = searchTerm.toLowerCase().trim();
    if (!term) return true;
    const title = (event.title || '').toLowerCase();
    const location = (event.locationText || '').toLowerCase();
    return title.includes(term) || location.includes(term);
  });
  const upcomingEvents = todayTs === null
    ? []
    : filteredEvents.filter((event: any) => new Date(event.startDate).getTime() >= todayTs);
  const pastEvents = todayTs === null
    ? filteredEvents
    : filteredEvents.filter((event: any) => new Date(event.startDate).getTime() < todayTs);
  const pastTotalPages = Math.max(1, Math.ceil(pastEvents.length / pageSize));
  const pastStart = (pastPage - 1) * pageSize;
  const pagedPast = pastEvents.slice(pastStart, pastStart + pageSize);

  useEffect(() => {
    fetchEvents();
  }, []);
  useEffect(() => {
    const d = new Date();
    d.setHours(0, 0, 0, 0);
    setTodayTs(d.getTime());
  }, []);

  const fetchEvents = async () => {
    try {
      const res = await fetch('/api/events');
      const data = await res.json();
      if (Array.isArray(data)) setEvents(data);
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  const resetForm = () => {
    setIsCreating(false);
    setEditingId(null);
    setFormData({ 
      title: '', 
      subtitle: '',
      startDate: '', 
      timeText: '', 
      locationText: '', 
      detailsContent: '',
      posterImage: '',
      galleryImages: []
    });
  };

  const handleEdit = (event: any) => {
    setFormData({
      title: event.title,
      subtitle: event.subtitle || '',
      startDate: event.startDate ? new Date(event.startDate).toISOString().split('T')[0] : '',
      timeText: event.timeText || '',
      locationText: event.locationText || '',
      detailsContent: event.detailsContent || '',
      posterImage: event.posterImage || '',
      galleryImages: event.galleryImages ? event.galleryImages.map((g: any) => g.url) : []
    });
    setEditingId(event._id);
    setIsCreating(true);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleDelete = async (id: string) => {
    if (!confirm('Are you sure you want to delete this event?')) return;
    try {
      const res = await fetch(`/api/events/${id}`, { method: 'DELETE' });
      if (res.ok) fetchEvents();
    } catch (error) {
      console.error(error);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    try {
      const url = editingId ? `/api/events/${editingId}` : '/api/events';
      const method = editingId ? 'PUT' : 'POST';

      const payload = {
        ...formData,
        galleryImages: formData.galleryImages.map(url => ({ url }))
      };

      const res = await fetch(url, {
        method: method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });
      
      if (res.ok) {
        resetForm();
        fetchEvents();
      }
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div>
      <div className="flex flex-col md:flex-row md:justify-between md:items-center gap-4 mb-8">
        <div>
          <h2 className="text-2xl font-bold text-slate-800">Events Management</h2>
          <p className="text-slate-500 text-sm">Manage upcoming and past events.</p>
        </div>
        {!isCreating && (
          <div className="flex-1 md:max-w-xs">
            <input
              value={searchTerm}
              onChange={(e) => {
                setSearchTerm(e.target.value);
                setPastPage(1);
              }}
              placeholder="Search events..."
              className="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-primary outline-none text-sm"
            />
          </div>
        )}
        {!isCreating && (
          <button 
            onClick={() => setIsCreating(true)}
            className="bg-primary hover:bg-primary-dark text-white px-4 py-2 rounded-lg font-medium transition flex items-center gap-2"
          >
            <Plus size={18} /> Add Event
          </button>
        )}
      </div>

      {isCreating ? (
        <div className="bg-white rounded-xl border border-slate-200 p-6 shadow-sm mb-6">
          <div className="flex justify-between items-center mb-6">
            <h3 className="text-lg font-bold">{editingId ? 'Edit Event' : 'Create New Event'}</h3>
            <button onClick={resetForm} className="text-slate-400 hover:text-slate-600"><X size={20} /></button>
          </div>
          <form onSubmit={handleSubmit} className="space-y-6">
            <div className="grid md:grid-cols-2 gap-6">
              <div className="space-y-4">
                 <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1">Event Title</label>
                    <input 
                      required
                      className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-primary outline-none"
                      value={formData.title}
                      onChange={e => setFormData({...formData, title: e.target.value})}
                      placeholder="e.g. Business Training Workshop"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1">Subtitle</label>
                    <input 
                      className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-primary outline-none"
                      value={formData.subtitle}
                      onChange={e => setFormData({...formData, subtitle: e.target.value})}
                      placeholder="e.g. Digital Marketing & AI..."
                    />
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-slate-700 mb-1">Date</label>
                      <input 
                        type="date"
                        required
                        className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-primary outline-none"
                        value={formData.startDate}
                        onChange={e => setFormData({...formData, startDate: e.target.value})}
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-slate-700 mb-1">Time</label>
                      <input 
                        className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-primary outline-none"
                        value={formData.timeText}
                        onChange={e => setFormData({...formData, timeText: e.target.value})}
                        placeholder="e.g. 10:30 AM - 4:30 PM"
                      />
                    </div>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1">Location</label>
                    <input 
                      className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-primary outline-none"
                      value={formData.locationText}
                      onChange={e => setFormData({...formData, locationText: e.target.value})}
                      placeholder="e.g. Montefiore Centre, London"
                    />
                  </div>
              </div>
              
              <div className="space-y-4">
                 <ImageUpload 
                    label="Poster Image (Single)"
                    value={formData.posterImage}
                    onChange={(val) => setFormData({...formData, posterImage: val as string})}
                  />
                  
                  <ImageUpload 
                    label="Event Gallery Images (Multiple)"
                    value={formData.galleryImages}
                    multiple={true}
                    onChange={(val) => setFormData({...formData, galleryImages: val as string[]})}
                  />
              </div>
            </div>

            <div className="col-span-2">
                <RichTextEditor 
                  label="Event Description / Details"
                  value={formData.detailsContent}
                  onChange={(val) => setFormData({...formData, detailsContent: val})}
                />
            </div>

            <div className="pt-4 border-t border-slate-100">
              <button 
                type="submit" 
                disabled={submitting}
                className="bg-primary hover:bg-primary-dark text-white px-6 py-2 rounded-lg font-medium transition flex items-center gap-2 disabled:opacity-50"
              >
                {submitting ? <Loader2 className="animate-spin" size={18} /> : <Save size={18} />} {editingId ? 'Update Event' : 'Save Event'}
              </button>
            </div>
          </form>
        </div>
      ) : null}

      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden shadow-sm">
        {loading ? (
          <div className="p-8 text-center"><Loader2 className="animate-spin mx-auto text-primary" /></div>
        ) : events.length === 0 ? (
          <div className="p-8 text-center py-16">
             <div className="w-16 h-16 bg-slate-50 rounded-full flex items-center justify-center mx-auto mb-4 text-slate-400">
               <Calendar size={32} />
             </div>
             <h3 className="text-lg font-medium text-slate-900">No events found</h3>
          </div>
        ) : (
          <div className="divide-y divide-slate-100">
            {upcomingEvents.length > 0 && (
              <div className="p-4 bg-emerald-50/70 border-b border-emerald-100">
                <h3 className="text-sm font-bold text-emerald-700 uppercase tracking-wider">
                  Upcoming Events ({upcomingEvents.length})
                </h3>
              </div>
            )}
            {upcomingEvents.map((event: any) => (
              <div key={event._id} className="p-4 flex items-center justify-between hover:bg-slate-50 group">
                <div className="flex items-center gap-4">
                  <div className="w-16 h-12 rounded bg-slate-100 flex items-center justify-center overflow-hidden border border-slate-200">
                    {event.posterImage ? (
                      <img src={event.posterImage} alt="" className="w-full h-full object-cover" />
                    ) : (
                      <Calendar size={20} className="text-slate-300" />
                    )}
                  </div>
                  <div>
                    <h4 className="font-bold text-slate-900">{event.title}</h4>
                    <p className="text-sm text-slate-500">{new Date(event.startDate).toLocaleDateString()} • {event.locationText}</p>
                  </div>
                  <span className="inline-flex items-center px-2.5 py-1 rounded-full text-[11px] font-bold bg-emerald-100 text-emerald-700">
                    Upcoming
                  </span>
                </div>
                <div className="flex items-center gap-3">
                  <button 
                    onClick={() => handleEdit(event)}
                    className="p-2 text-slate-400 hover:text-blue-600 rounded-full"
                  >
                    <Pencil size={16} />
                  </button>
                  <button 
                    onClick={() => handleDelete(event._id)}
                    className="p-2 text-slate-400 hover:text-red-600 rounded-full"
                  >
                    <Trash2 size={16} />
                  </button>
                </div>
              </div>
            ))}

            {pastEvents.length > 0 && (
              <div className="p-4 bg-slate-50 border-y border-slate-100">
                <h3 className="text-sm font-bold text-slate-600 uppercase tracking-wider">
                  Past Events ({pastEvents.length})
                </h3>
              </div>
            )}
            {pagedPast.map((event: any) => (
              <div key={event._id} className="p-4 flex items-center justify-between hover:bg-slate-50 group">
                <div className="flex items-center gap-4">
                  <div className="w-16 h-12 rounded bg-slate-100 flex items-center justify-center overflow-hidden border border-slate-200">
                    {event.posterImage ? (
                      <img src={event.posterImage} alt="" className="w-full h-full object-cover" />
                    ) : (
                      <Calendar size={20} className="text-slate-300" />
                    )}
                  </div>
                  <div>
                    <h4 className="font-bold text-slate-900">{event.title}</h4>
                    <p className="text-sm text-slate-500">{new Date(event.startDate).toLocaleDateString()} • {event.locationText}</p>
                  </div>
                  <span className="inline-flex items-center px-2.5 py-1 rounded-full text-[11px] font-bold bg-slate-200 text-slate-700">
                    Past
                  </span>
                </div>
                <div className="flex items-center gap-3">
                  <button 
                    onClick={() => handleEdit(event)}
                    className="p-2 text-slate-400 hover:text-blue-600 rounded-full"
                  >
                    <Pencil size={16} />
                  </button>
                  <button 
                    onClick={() => handleDelete(event._id)}
                    className="p-2 text-slate-400 hover:text-red-600 rounded-full"
                  >
                    <Trash2 size={16} />
                  </button>
                </div>
              </div>
            ))}
            {pastEvents.length > 0 && (
              <div className="p-4 flex flex-col md:flex-row md:items-center md:justify-between gap-3 border-t border-slate-100">
                <p className="text-xs text-slate-500">Showing {pagedPast.length} of {pastEvents.length} past events</p>
                <div className="flex items-center gap-2">
                  <button
                    onClick={() => setPastPage((p) => Math.max(1, p - 1))}
                    disabled={pastPage === 1}
                    className="px-3 py-1.5 rounded-lg border border-slate-200 text-sm disabled:opacity-50"
                  >
                    Prev
                  </button>
                  <span className="text-sm text-slate-600">Page {pastPage} of {pastTotalPages}</span>
                  <button
                    onClick={() => setPastPage((p) => Math.min(pastTotalPages, p + 1))}
                    disabled={pastPage === pastTotalPages}
                    className="px-3 py-1.5 rounded-lg border border-slate-200 text-sm disabled:opacity-50"
                  >
                    Next
                  </button>
                </div>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}
