const { useState, useEffect, useMemo } = React;

window.AdminDashboard = function AdminDashboard({ events, setEvents }) {
  const [activeTab, setActiveTab] = useState('events');

  // --- EVENTS LOGIC ---
  const [editingEventId, setEditingEventId] = useState(null);
  
  // Teams are dynamic now, load them for select options
  const [teams, setTeams] = useState(window.DataManager.getTeams());

  const initialEventForm = {
    title: '',
    date: new Date().toISOString().split('T')[0],
    startTime: '09:00',
    endTime: '10:00',
    team: teams.length > 0 ? teams[0].name : '',
    eventType: window.DataManager.getEventTypes()[0],
    location: '',
    isGroundBooking: false,
    notes: ''
  };
  const [eventForm, setEventForm] = useState(initialEventForm);

  // --- TEAMS LOGIC ---
  const [editingTeamId, setEditingTeamId] = useState(null);
  const initialTeamForm = { name: '', bgColor: '#3b82f6', textColor: '#ffffff' };
  const [teamForm, setTeamForm] = useState(initialTeamForm);

  useEffect(() => {
    if (window.lucide) window.lucide.createIcons();
  });

  const timeSlots = useMemo(() => {
    const slots = [];
    for (let h = 0; h < 24; h++) {
      for (let m = 0; m < 60; m += 30) {
        slots.push(`${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`);
      }
    }
    return slots;
  }, []);

  // Duration Helper
  const calcDuration = (start, end) => {
    if (!start || !end) return 0;
    const [sh, sm] = start.split(':').map(Number);
    const [eh, em] = end.split(':').map(Number);
    let diff = (eh * 60 + em) - (sh * 60 + sm);
    if (diff < 0) diff += 24 * 60; // handle overnight slightly
    return diff;
  };

  const currentDurationHrs = (calcDuration(eventForm.startTime, eventForm.endTime) / 60).toFixed(1);

  // --- EVENT HANDLERS ---
  const handleEventInputChange = (e) => {
    const { name, value, type, checked } = e.target;
    setEventForm(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value
    }));
  };

  const handleEventSubmit = (e) => {
    e.preventDefault();
    const duration = calcDuration(eventForm.startTime, eventForm.endTime);
    if (duration === 0) {
      alert("Start Time and End Time cannot be the same.");
      return;
    }
    if (editingEventId) {
      const updated = window.DataManager.updateEvent({ ...eventForm, id: editingEventId, duration });
      setEvents(prev => prev.map(ev => ev.id === editingEventId ? updated : ev));
      setEditingEventId(null);
    } else {
      const newEvent = window.DataManager.addEvent({ ...eventForm, duration });
      setEvents(prev => [...prev, newEvent]);
    }
    setEventForm({ ...initialEventForm, team: teams[0]?.name || '' });
  };

  const handleEditEvent = (event) => {
    setEditingEventId(event.id);
    setEventForm({ ...event });
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleDeleteEvent = (id) => {
    if (confirm('Are you sure you want to delete this event?')) {
      window.DataManager.deleteEvent(id);
      setEvents(prev => prev.filter(e => e.id !== id));
      if (editingEventId === id) {
        setEditingEventId(null);
        setEventForm({ ...initialEventForm, team: teams[0]?.name || '' });
      }
    }
  };

  // --- TEAM HANDLERS ---
  const handleTeamInputChange = (e) => {
    const { name, value } = e.target;
    setTeamForm(prev => ({ ...prev, [name]: value }));
  };

  const handleTeamSubmit = (e) => {
    e.preventDefault();
    if (editingTeamId) {
      const updated = window.DataManager.updateTeam({ ...teamForm, id: editingTeamId });
      setTeams(prev => prev.map(t => t.id === editingTeamId ? updated : t));
      setEditingTeamId(null);
    } else {
      const newTeam = window.DataManager.addTeam({ ...teamForm });
      setTeams(prev => [...prev, newTeam]);
    }
    setTeamForm(initialTeamForm);
  };

  const handleEditTeam = (team) => {
    setEditingTeamId(team.id);
    setTeamForm({ ...team });
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleDeleteTeam = (id) => {
    if (confirm('Are you sure you want to delete this team? Existing events may lose their color styling.')) {
      window.DataManager.deleteTeam(id);
      setTeams(prev => prev.filter(t => t.id !== id));
      if (editingTeamId === id) {
        setEditingTeamId(null);
        setTeamForm(initialTeamForm);
      }
    }
  };

  // Color calculating logic for contrast
  const handleBgColorChange = (e) => {
    const hex = e.target.value;
    const r = parseInt(hex.slice(1, 3), 16);
    const g = parseInt(hex.slice(3, 5), 16);
    const b = parseInt(hex.slice(5, 7), 16);
    const luma = 0.2126 * r + 0.7152 * g + 0.0722 * b; // SMPTE C, Rec. 709 weightings
    const textColor = luma < 128 ? '#ffffff' : '#1f2937';
    
    setTeamForm(prev => ({
      ...prev,
      bgColor: hex,
      textColor: textColor
    }));
  };

  return (
    <div className="max-w-6xl mx-auto">
      {/* Tabs */}
      <div className="flex gap-2 mb-8 bg-gray-100 p-1.5 rounded-xl max-w-fit">
        <button 
          onClick={() => setActiveTab('events')} 
          className={`px-5 py-2 rounded-lg text-sm font-bold transition-all ${activeTab === 'events' ? 'bg-white text-blue-600 shadow-sm' : 'text-gray-600 hover:text-gray-900'}`}
        >
          Manage Events
        </button>
        <button 
          onClick={() => setActiveTab('teams')} 
          className={`px-5 py-2 rounded-lg text-sm font-bold transition-all ${activeTab === 'teams' ? 'bg-white text-blue-600 shadow-sm' : 'text-gray-600 hover:text-gray-900'}`}
        >
          Manage Teams
        </button>
      </div>

      {activeTab === 'events' && (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* Form Section */}
          <div className="lg:col-span-1">
            <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6 sticky top-6">
              <h2 className="text-xl font-bold mb-6 flex items-center">
                <i data-lucide={editingEventId ? "edit" : "plus-circle"} className="w-5 h-5 mr-2 text-blue-600"></i>
                {editingEventId ? 'Edit Event' : 'Add New Event'}
              </h2>
              
              <form onSubmit={handleEventSubmit} className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Event Title</label>
                  <input required type="text" name="title" value={eventForm.title} onChange={handleEventInputChange} className="w-full bg-white border-2 border-gray-200 rounded-lg shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm py-3 px-3 hover:border-gray-300 transition-colors outline-none" placeholder="e.g. Training Session" />
                </div>
                
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Date</label>
                  <input required type="date" name="date" value={eventForm.date} onChange={handleEventInputChange} className="w-full bg-white border-2 border-gray-200 rounded-lg shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm py-3 px-3 hover:border-gray-300 transition-colors outline-none" />
                </div>
                
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">Start Time</label>
                    <select name="startTime" value={eventForm.startTime} onChange={handleEventInputChange} className="w-full bg-white border-2 border-gray-200 rounded-lg shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm py-3 px-3 hover:border-gray-300 transition-colors outline-none">
                      {timeSlots.map(time => <option key={time} value={time}>{time}</option>)}
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      End Time <span className="text-xs text-gray-400 font-normal ml-1">({currentDurationHrs} hrs)</span>
                    </label>
                    <select name="endTime" value={eventForm.endTime} onChange={handleEventInputChange} className="w-full bg-white border-2 border-gray-200 rounded-lg shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm py-3 px-3 hover:border-gray-300 transition-colors outline-none">
                      {timeSlots.map(time => <option key={time} value={time}>{time}</option>)}
                    </select>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">Team/Category</label>
                    <window.CustomTeamSelect 
                      value={eventForm.team} 
                      onChange={handleEventInputChange} 
                      teams={teams}
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">Event Type</label>
                    <window.CustomSelect 
                      name="eventType"
                      value={eventForm.eventType} 
                      onChange={handleEventInputChange} 
                      options={window.DataManager.getEventTypes()}
                    />
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Location</label>
                  <input required type="text" name="location" value={eventForm.location} onChange={handleEventInputChange} className="w-full bg-white border-2 border-gray-200 rounded-lg shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm py-3 px-3 hover:border-gray-300 transition-colors outline-none" placeholder="e.g. Main Pitch" />
                </div>

                <label className="flex items-center gap-2 text-sm text-gray-700 cursor-pointer bg-gray-50 px-3 py-2 rounded-lg border border-gray-200 hover:bg-gray-100 transition-colors">
                  <input type="checkbox" name="isGroundBooking" checked={eventForm.isGroundBooking} onChange={handleEventInputChange} className="rounded text-blue-600 focus:ring-blue-500 w-4 h-4 cursor-pointer" />
                  Reserve St Andrew's Ground Slot
                </label>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Notes (Optional)</label>
                  <textarea name="notes" value={eventForm.notes} onChange={handleEventInputChange} rows="3" className="w-full bg-white border-2 border-gray-200 rounded-lg shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm py-3 px-3 hover:border-gray-300 transition-colors outline-none"></textarea>
                </div>

                <div className="pt-2 flex gap-3">
                  {editingEventId && (
                    <button type="button" onClick={() => { setEditingEventId(null); setEventForm({ ...initialEventForm, team: teams[0]?.name || '' }); }} className="flex-1 px-4 py-2 text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-lg text-sm font-medium transition-colors">
                      Cancel
                    </button>
                  )}
                  <button type="submit" className="flex-1 px-4 py-2 bg-blue-600 text-white hover:bg-blue-700 rounded-lg text-sm font-medium transition-colors shadow-sm flex justify-center items-center">
                    <i data-lucide="save" className="w-4 h-4 mr-2"></i>
                    {editingEventId ? 'Update Event' : 'Save Event'}
                  </button>
                </div>
              </form>
            </div>
          </div>

          {/* List Section */}
          <div className="lg:col-span-2">
            <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
              <div className="p-6 border-b border-gray-200 flex justify-between items-center bg-gray-50/50">
                <h2 className="text-xl font-bold flex items-center">
                  <i data-lucide="list" className="w-5 h-5 mr-2 text-gray-500"></i>
                  Manage Events
                </h2>
                <span className="bg-blue-100 text-blue-800 text-xs font-semibold px-2.5 py-0.5 rounded-full">{events.length} Total</span>
              </div>
              
              <div className="divide-y divide-gray-200">
                {events.sort((a, b) => new Date(b.date) - new Date(a.date)).map(event => {
                  const teamData = window.DataManager.getTeamByName(event.team);
                  return (
                    <div key={event.id} className="p-4 hover:bg-gray-50 transition-colors flex items-center justify-between gap-4">
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2 mb-1">
                          <span className="w-3 h-3 rounded-full" style={{ backgroundColor: teamData.bgColor }}></span>
                          <h3 className="text-sm font-bold text-gray-900 truncate">{event.title}</h3>
                          {event.isGroundBooking && <span className="bg-gray-100 text-gray-600 text-[10px] uppercase font-bold px-1.5 py-0.5 rounded">St Andrew's Ground</span>}
                        </div>
                        <p className="text-sm text-gray-500 flex items-center gap-3">
                          <span><i data-lucide="calendar" className="w-3.5 h-3.5 inline mr-1"></i>{event.date}</span>
                          <span><i data-lucide="clock" className="w-3.5 h-3.5 inline mr-1"></i>{event.startTime} - {event.endTime}</span>
                          <span className="hidden sm:inline"><i data-lucide="users" className="w-3.5 h-3.5 inline mr-1"></i>{event.team}</span>
                        </p>
                      </div>
                      <div className="flex items-center gap-2">
                        <button onClick={() => handleEditEvent(event)} className="p-2 text-gray-400 hover:text-blue-600 bg-white hover:bg-blue-50 border border-gray-200 rounded transition-colors" title="Edit">
                          <i data-lucide="edit-2" className="w-4 h-4"></i>
                        </button>
                        <button onClick={() => handleDeleteEvent(event.id)} className="p-2 text-gray-400 hover:text-red-600 bg-white hover:bg-red-50 border border-gray-200 rounded transition-colors" title="Delete">
                          <i data-lucide="trash-2" className="w-4 h-4"></i>
                        </button>
                      </div>
                    </div>
                  );
                })}
                {events.length === 0 && (
                  <div className="p-12 text-center text-gray-500">
                    <i data-lucide="calendar-x" className="w-12 h-12 mx-auto mb-3 opacity-20"></i>
                    <p>No events found. Create one to get started.</p>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      )}

      {activeTab === 'teams' && (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* Team Form */}
          <div className="lg:col-span-1">
            <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6 sticky top-6">
              <h2 className="text-xl font-bold mb-6 flex items-center">
                <i data-lucide={editingTeamId ? "edit" : "plus-circle"} className="w-5 h-5 mr-2 text-blue-600"></i>
                {editingTeamId ? 'Edit Team' : 'Add New Team'}
              </h2>
              
              <form onSubmit={handleTeamSubmit} className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Team Name</label>
                  <input required type="text" name="name" value={teamForm.name} onChange={handleTeamInputChange} className="w-full bg-white border-2 border-gray-200 rounded-lg shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm py-3 px-3 hover:border-gray-300 transition-colors outline-none" placeholder="e.g. Under-19" />
                </div>
                
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Badge Color</label>
                  <div className="flex items-center gap-3">
                    <input required type="color" name="bgColor" value={teamForm.bgColor} onChange={handleBgColorChange} className="w-12 h-12 p-1 rounded bg-white border border-gray-200 cursor-pointer" />
                    <div className="flex-1 text-sm text-gray-500">
                      Select the primary color for this team's badge. Text color will adjust automatically.
                    </div>
                  </div>
                </div>

                {/* Preview Box */}
                <div className="pt-2">
                  <label className="block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-2">Preview</label>
                  <div className="p-2 text-sm rounded shadow-sm text-center font-semibold" style={{ backgroundColor: teamForm.bgColor, color: teamForm.textColor }}>
                    {teamForm.name || 'Team Name'}
                  </div>
                </div>

                <div className="pt-4 flex gap-3">
                  {editingTeamId && (
                    <button type="button" onClick={() => { setEditingTeamId(null); setTeamForm(initialTeamForm); }} className="flex-1 px-4 py-2 text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-lg text-sm font-medium transition-colors">
                      Cancel
                    </button>
                  )}
                  <button type="submit" className="flex-1 px-4 py-2 bg-blue-600 text-white hover:bg-blue-700 rounded-lg text-sm font-medium transition-colors shadow-sm flex justify-center items-center">
                    <i data-lucide="save" className="w-4 h-4 mr-2"></i>
                    {editingTeamId ? 'Update Team' : 'Save Team'}
                  </button>
                </div>
              </form>
            </div>
          </div>

          {/* Teams List */}
          <div className="lg:col-span-2">
            <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
              <div className="p-6 border-b border-gray-200 flex justify-between items-center bg-gray-50/50">
                <h2 className="text-xl font-bold flex items-center">
                  <i data-lucide="users" className="w-5 h-5 mr-2 text-gray-500"></i>
                  Manage Teams
                </h2>
                <span className="bg-blue-100 text-blue-800 text-xs font-semibold px-2.5 py-0.5 rounded-full">{teams.length} Teams</span>
              </div>
              
              <div className="divide-y divide-gray-200">
                {teams.map(team => (
                  <div key={team.id} className="p-4 hover:bg-gray-50 transition-colors flex items-center justify-between gap-4">
                    <div className="flex items-center gap-4">
                      <div className="w-10 h-10 rounded-full flex items-center justify-center font-bold text-lg shadow-sm" style={{ backgroundColor: team.bgColor, color: team.textColor }}>
                        {team.name.charAt(0).toUpperCase()}
                      </div>
                      <div>
                        <h3 className="text-sm font-bold text-gray-900">{team.name}</h3>
                        <p className="text-xs text-gray-500 mt-0.5">Color: <span className="font-mono">{team.bgColor}</span></p>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      <button onClick={() => handleEditTeam(team)} className="p-2 text-gray-400 hover:text-blue-600 bg-white hover:bg-blue-50 border border-gray-200 rounded transition-colors" title="Edit">
                        <i data-lucide="edit-2" className="w-4 h-4"></i>
                      </button>
                      <button onClick={() => handleDeleteTeam(team.id)} className="p-2 text-gray-400 hover:text-red-600 bg-white hover:bg-red-50 border border-gray-200 rounded transition-colors" title="Delete">
                        <i data-lucide="trash-2" className="w-4 h-4"></i>
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};
