import { useEffect, useState, useRef } from 'react';
import { createPortal } from 'react-dom';
import { useClubsStore, Club } from '../../store/clubs';
import { useAuthStore } from '../../store/auth';
import { 
  Trophy, Users, Search, Plus, 
  ChevronRight, Bell, CheckCircle2, ListChecks, MessageSquare, UserMinus,
  Edit2, X, Gamepad2, Play
} from 'lucide-react';
import api from '../../store/api';
import ExtracurricularChat from '../../components/ExtracurricularChat';
import EdutainmentGames from '../../components/EdutainmentGames';

export default function TeacherExtracurriculars() {
  const { user } = useAuthStore();
  const { 
    clubs, memberships, announcements, attendance, loading,
    fetchClubs, fetchMemberships, fetchAnnouncements, fetchAttendance,
    createClub, updateClub, postAnnouncement, markAttendance, joinClub, leaveClub
  } = useClubsStore();

  const [activeTab, setActiveTab] = useState('manage'); // manage, announcements, rollcall
  const [selectedClub, setSelectedClub] = useState<Club | null>(null);
  const [viewArena, setViewArena] = useState(false);
  
  const [showClubModal, setShowClubModal] = useState(false);
  const [showAnnouncementModal, setShowAnnouncementModal] = useState(false);

  const [clubForm, setClubForm] = useState({
    name: '', type: 'club', description: '', schedule: '', max_members: 0, teacher_in_charge_id: user?.id
  });

  const [announcementForm, setAnnouncementForm] = useState({
    title: '', content: ''
  });

  const [attendanceDate, setAttendanceDate] = useState(new Date().toISOString().split('T')[0]);
  const [attendanceData, setAttendanceData] = useState<any>({}); // studentId -> status

  const [students, setStudents] = useState<any[]>([]);
  const [teachers, setTeachers] = useState<any[]>([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedStudentId, setSelectedStudentId] = useState<string>('');
  const [showEnrollModal, setShowEnrollModal] = useState(false);
  const [enrollSubmitting, setEnrollSubmitting] = useState(false);

  const [studentSearch, setStudentSearch] = useState('');
  const [showDropdown, setShowDropdown] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  const [showEditModal, setShowEditModal] = useState(false);
  const [editForm, setEditForm] = useState({
    name: '', type: 'club' as 'club' | 'sport', description: '', schedule: '', max_members: 0, teacher_in_charge_id: user?.id, status: 'active' as 'active' | 'inactive'
  });
  const [editSubmitting, setEditSubmitting] = useState(false);

  const handleOpenEdit = (club: Club) => {
    setEditForm({
      name: club.name,
      type: club.type,
      description: club.description || '',
      schedule: club.schedule || '',
      max_members: club.max_members || 0,
      teacher_in_charge_id: club.teacher_in_charge_id,
      status: club.status || 'active'
    });
    setShowEditModal(true);
  };

  const handleSaveEdit = async () => {
    if (!selectedClub) return;
    setEditSubmitting(true);
    try {
      await updateClub(selectedClub.id, {
        ...editForm,
        max_members: editForm.max_members || null
      });
      const updatedClub = {
        ...selectedClub,
        ...editForm,
        max_members: editForm.max_members || undefined
      };
      setSelectedClub(updatedClub as Club);
      setShowEditModal(false);
    } catch (err) {
      alert('Failed to update activity details');
    } finally {
      setEditSubmitting(false);
    }
  };

  const fetchAllStudents = async () => {
    try {
      const res = await api.get('/users', { params: { role: 'student', limit: 1000 } });
      const data = Array.isArray(res.data) ? res.data : (res.data?.users || []);
      setStudents(data);
    } catch (err) {
      console.error('Failed to fetch students', err);
    }
  };

  const fetchTeachers = async () => {
    try {
      const res = await api.get('/users', { params: { role: 'teacher', limit: 500 } });
      const data = Array.isArray(res.data) ? res.data : (res.data?.users || []);
      setTeachers(data);
    } catch (err) {
      console.error('Failed to fetch teachers', err);
    }
  };

  const filteredStudents = students
    .filter(s => !memberships.some(m => m.student_id === s.id && m.status === 'active'))
    .filter(s => {
      const fullName = `${s.first_name} ${s.last_name}`.toLowerCase();
      const email = s.email.toLowerCase();
      const query = studentSearch.toLowerCase();
      return fullName.includes(query) || email.includes(query);
    });

  const filteredMyClubs = clubs
    .filter(c => c.teacher_in_charge_id === user?.id || user?.role === 'clubs_head')
    .filter(c => c.name.toLowerCase().includes(searchQuery.toLowerCase()) || (c.description || '').toLowerCase().includes(searchQuery.toLowerCase()));

  useEffect(() => {
    if (showEnrollModal) {
      fetchAllStudents();
      setStudentSearch('');
      setSelectedStudentId('');
      setShowDropdown(false);
    }
  }, [showEnrollModal]);

  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setShowDropdown(false);
      }
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  useEffect(() => {
    fetchClubs();
    fetchTeachers();
  }, []);

  useEffect(() => {
    if (selectedClub) {
      fetchMemberships(selectedClub.id);
      fetchAnnouncements(selectedClub.id);
      fetchAttendance(selectedClub.id, attendanceDate);
    }
  }, [selectedClub, attendanceDate]);

  // Pre-fill attendance data when memberships or existing attendance changes
  useEffect(() => {
    if (activeTab === 'rollcall' && memberships.length > 0) {
      const data: any = {};
      memberships.forEach(m => {
        const existing = attendance.find(a => a.student_id === m.student_id);
        data[m.student_id] = existing ? existing.status : 'present'; // default present
      });
      setAttendanceData(data);
    }
  }, [activeTab, memberships, attendance]);

  const handleSaveClub = async () => {
    try {
      await createClub({ ...clubForm, max_members: clubForm.max_members || null });
      setShowClubModal(false);
    } catch (err) { alert('Failed to create club'); }
  };

  const handlePostAnnouncement = async () => {
    if (!selectedClub) return;
    try {
      await postAnnouncement({ club_id: selectedClub.id, ...announcementForm });
      setShowAnnouncementModal(false);
      setAnnouncementForm({ title: '', content: '' });
    } catch (err) { alert('Failed to post announcement'); }
  };

  const handleSaveAttendance = async () => {
    if (!selectedClub) return;
    const records = Object.keys(attendanceData).map(studentId => ({
      club_id: selectedClub.id,
      student_id: Number(studentId),
      date: attendanceDate,
      status: attendanceData[studentId]
    }));
    try {
      await markAttendance(records);
      alert('Attendance saved successfully');
    } catch (err) { alert('Failed to save attendance'); }
  };

  return (
    <div className="space-y-10 animate-in fade-in duration-700 pb-10">
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
        <div>
          <h2 className="text-3xl font-black text-text tracking-tight uppercase">Activities Management</h2>
          <nav className="flex text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted dark:text-text-light gap-2 items-center mt-1">
            <span>Teacher Portal</span>
            <ChevronRight size={12} className="text-text-muted/30" />
            <span className="text-primary">Clubs & Sports</span>
          </nav>
        </div>
        <div className="flex gap-3">
          <button 
            onClick={() => setShowClubModal(true)}
            className="flex items-center gap-2 px-6 py-2.5 bg-primary text-white rounded-xl font-bold text-sm hover:bg-primary/90 transition-all shadow-lg active:scale-95"
          >
            <Plus size={18} />
            Create Activity
          </button>
        </div>
      </div>

      {/* Featured Edutainment Banner */}
      {!viewArena && (
        <div className="bg-gradient-to-r from-primary/10 via-primary/5 to-transparent border border-primary/20 rounded-[2.5rem] p-6 md:p-8 shadow-sm flex flex-col md:flex-row justify-between items-start md:items-center gap-6 relative overflow-hidden group">
          <div className="absolute top-0 right-0 w-48 h-48 bg-primary/10 rounded-bl-[10rem] -z-10 group-hover:scale-105 transition-transform"></div>
          <div className="flex items-start gap-4 md:gap-6">
            <div className="w-14 h-14 rounded-2xl bg-primary text-white flex items-center justify-center font-black shadow-lg shadow-primary/20 animate-pulse">
              <Gamepad2 size={28} />
            </div>
            <div>
              <h3 className="text-xl md:text-2xl font-black text-text tracking-tight uppercase flex items-center gap-2">
                Edutainment Arena
                <span className="bg-primary/20 text-primary text-[0.6rem] px-2 py-0.5 rounded-full font-black uppercase tracking-widest">New</span>
              </h3>
              <p className="text-xs text-text-muted mt-1 max-w-xl font-medium">
                Manage and publish crossword puzzles, check student standings, and explore other educational games in the arena.
              </p>
            </div>
          </div>
          <button 
            onClick={() => setViewArena(true)}
            className="px-6 py-3 bg-primary text-white rounded-xl font-black text-xs uppercase tracking-widest hover:bg-primary/90 transition-all shadow-lg active:scale-95 flex items-center gap-2 shrink-0"
          >
            <Play size={14} /> Enter Arena
          </button>
        </div>
      )}

      {viewArena ? (
        <EdutainmentGames onClose={() => setViewArena(false)} />
      ) : (
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
        {/* Left Column: Clubs List */}
        <div className="lg:col-span-4 space-y-6">
          <div className="bg-card border border-border rounded-[2.5rem] p-6 shadow-sm">
            <h3 className="text-sm font-black text-text uppercase tracking-widest mb-4">My Activities</h3>
            
            {/* Sidebar Search Bar */}
            <div className="relative group mb-4">
              <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted group-focus-within:text-primary transition-colors" />
              <input 
                type="text" 
                className="w-full bg-muted/50 border border-border rounded-xl pl-9 pr-3 py-2 text-xs font-medium focus:outline-none focus:ring-2 focus:ring-primary/10 focus:bg-card focus:border-primary transition-all text-text"
                placeholder="Search activities..."
                value={searchQuery}
                onChange={e => setSearchQuery(e.target.value)}
              />
            </div>

            <div className="space-y-3">
              {filteredMyClubs.map(c => (
                <div 
                  key={c.id} 
                  onClick={() => setSelectedClub(c)}
                  className={`p-4 rounded-2xl border cursor-pointer transition-all flex items-center gap-4 ${selectedClub?.id === c.id ? 'bg-primary/5 border-primary text-primary' : 'bg-muted/30 border-border text-text hover:bg-muted/50'}`}
                >
                  <div className={`w-10 h-10 rounded-xl flex items-center justify-center ${selectedClub?.id === c.id ? 'bg-primary/10' : 'bg-muted'}`}>
                    {c.type === 'sport' ? <Trophy size={18} /> : <Users size={18} />}
                  </div>
                  <div>
                    <h4 className="font-bold text-sm">{c.name}</h4>
                    <p className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted dark:text-text-light opacity-80 dark:opacity-100">{c.current_members || 0} Members</p>
                  </div>
                </div>
              ))}
              {clubs.filter(c => c.teacher_in_charge_id === user?.id || user?.role === 'clubs_head').length === 0 ? (
                <div className="p-6 text-center text-text-muted">
                  <p className="text-xs font-bold uppercase tracking-widest">No activities managed</p>
                </div>
              ) : filteredMyClubs.length === 0 ? (
                <div className="p-6 text-center text-text-muted">
                  <p className="text-xs font-bold uppercase tracking-widest">No matching activities</p>
                </div>
              ) : null}
            </div>
          </div>
        </div>

        {/* Right Column: Details & Management */}
        <div className="lg:col-span-8">
          {!selectedClub ? (
            <div className="bg-card border-2 border-dashed border-border rounded-[3rem] py-24 text-center">
              <Trophy size={64} className="mx-auto text-text-muted/20 mb-6" />
              <h3 className="text-xl font-black text-text mb-2 uppercase tracking-tighter">Select an Activity</h3>
              <p className="text-text-muted font-medium max-w-sm mx-auto">Choose a club or sport from your list to manage memberships, post announcements, or take attendance.</p>
            </div>
          ) : (
            <div className="space-y-6">
              {/* Activity Info Header Card */}
              <div className="bg-card border border-border rounded-[2.5rem] p-8 shadow-sm flex flex-col md:flex-row justify-between items-start md:items-center gap-6 relative overflow-hidden">
                <div className="absolute top-0 right-0 w-32 h-32 bg-primary/5 rounded-bl-[4rem] -z-10"></div>
                <div className="flex items-start gap-6">
                  <div className={`w-14 h-14 rounded-2xl flex items-center justify-center text-white font-black shadow-lg ${selectedClub.type === 'sport' ? 'bg-orange-500 shadow-orange-500/20' : 'bg-blue-600 shadow-blue-600/20'}`}>
                    {selectedClub.type === 'sport' ? <Trophy size={24} /> : <Users size={24} />}
                  </div>
                  <div>
                    <div className="flex items-center gap-2 flex-wrap">
                      <h3 className="text-2xl font-black text-text tracking-tight uppercase">{selectedClub.name}</h3>
                      <span className={`px-2.5 py-0.5 rounded-md text-[0.6rem] font-black uppercase tracking-widest border ${
                        selectedClub.type === 'sport' ? 'bg-orange-50 text-orange-600 border-orange-100 dark:bg-orange-950/30 dark:text-orange-400 dark:border-orange-900/50' : 'bg-blue-50 text-blue-600 border-blue-100 dark:bg-blue-950/30 dark:text-blue-400 dark:border-blue-900/50'
                      }`}>
                        {selectedClub.type}
                      </span>
                    </div>
                    {selectedClub.description && (
                      <p className="text-sm font-medium text-text-muted dark:text-text-secondary mt-2 max-w-xl">{selectedClub.description}</p>
                    )}
                    <div className="flex gap-4 mt-4 flex-wrap text-[0.7rem] font-black uppercase tracking-widest text-text-muted dark:text-text-light">
                      <div className="flex items-center gap-1.5">
                        <span className="text-primary font-bold">Schedule:</span> {selectedClub.schedule || 'TBA'}
                      </div>
                      <div className="flex items-center gap-1.5">
                        <span className="text-primary font-bold">Capacity:</span> {selectedClub.current_members || 0} / {selectedClub.max_members || '∞'}
                      </div>
                    </div>
                  </div>
                </div>
                <button
                  onClick={() => handleOpenEdit(selectedClub)}
                  className="px-5 py-2.5 bg-primary/5 hover:bg-primary/10 text-primary border border-primary/20 hover:border-primary/30 rounded-xl font-black text-[0.65rem] uppercase tracking-widest transition-all flex items-center justify-center gap-2 active:scale-95"
                >
                  <Edit2 size={14} /> Edit Details
                </button>
              </div>

              <div className="bg-card border border-border rounded-[2.5rem] p-2 shadow-sm flex flex-col lg:flex-row items-stretch lg:items-center gap-4">
                <div className="flex p-1 bg-muted/50 rounded-2xl flex-grow lg:flex-grow-0 min-w-0">
                  {[
                    { id: 'manage', label: 'Members', icon: Users },
                    { id: 'announcements', label: 'Announcements', icon: Bell },
                    { id: 'rollcall', label: 'Roll Call', icon: ListChecks },
                    { id: 'chat', label: 'Chat Room', icon: MessageSquare },
                  ].map((tab) => (
                    <button
                      key={tab.id}
                      onClick={() => setActiveTab(tab.id)}
                      className={`
                        flex-1 px-6 py-2.5 rounded-xl text-[0.7rem] font-black uppercase tracking-widest transition-all whitespace-nowrap flex items-center justify-center gap-2
                        ${activeTab === tab.id ? 'bg-card text-primary shadow-sm ring-1 ring-border' : 'text-text-muted hover:text-text'}
                      `}
                    >
                      <tab.icon size={14} />
                      {tab.label}
                    </button>
                  ))}
                </div>
              </div>

              <div className="bg-card border border-border rounded-[2.5rem] p-8 shadow-sm">
                {activeTab === 'manage' ? (
                  <div>
                    <div className="flex justify-between items-center mb-6">
                      <h3 className="text-lg font-black text-text uppercase tracking-tight">Current Enrollees</h3>
                      <button 
                        onClick={() => setShowEnrollModal(true)}
                        className="px-4 py-2 bg-primary text-white rounded-xl font-bold text-xs uppercase tracking-widest flex items-center gap-1.5 active:scale-95 transition-all"
                      >
                        <Plus size={14} /> Add Student
                      </button>
                    </div>
                    <div className="overflow-x-auto">
                      <table className="w-full text-left">
                        <thead>
                          <tr className="bg-muted/50 border-b border-border">
                            <th className="px-6 py-4 text-[0.65rem] font-black text-primary uppercase tracking-widest">Student</th>
                            <th className="px-6 py-4 text-[0.65rem] font-black text-primary uppercase tracking-widest">Joined</th>
                            <th className="px-6 py-4 text-[0.65rem] font-black text-primary uppercase tracking-widest">Status</th>
                            <th className="px-6 py-4 text-[0.65rem] font-black text-primary uppercase tracking-widest text-right">Actions</th>
                          </tr>
                        </thead>
                        <tbody className="divide-y divide-border">
                          {memberships.length === 0 ? (
                            <tr><td colSpan={4} className="px-6 py-8 text-center text-text-muted text-sm font-medium">No members enrolled</td></tr>
                          ) : (
                            memberships.map(m => (
                              <tr key={m.id} className="hover:bg-muted/30">
                                <td className="px-6 py-4">
                                  <p className="text-sm font-bold text-text">{m.first_name} {m.last_name}</p>
                                </td>
                                <td className="px-6 py-4 text-xs font-bold text-text-muted">{new Date(m.join_date).toLocaleDateString()}</td>
                                <td className="px-6 py-4">
                                  <span className={`px-2.5 py-1 rounded-lg text-[0.6rem] font-black uppercase tracking-widest border ${m.status === 'active' ? 'bg-emerald-50 text-emerald-600 border-emerald-100 dark:bg-emerald-950/30 dark:text-emerald-400 dark:border-emerald-900/50' : 'bg-rose-50 text-rose-600 border-rose-100 dark:bg-rose-950/30 dark:text-rose-400 dark:border-rose-900/50'}`}>
                                    {m.status}
                                  </span>
                                </td>
                                <td className="px-6 py-4 text-right">
                                  {m.status === 'active' && (
                                    <button
                                      onClick={async () => {
                                        if (window.confirm(`Are you sure you want to remove ${m.first_name} ${m.last_name} from this activity?`)) {
                                          try {
                                            await leaveClub(selectedClub.id, m.student_id);
                                            fetchMemberships(selectedClub.id);
                                          } catch (err) {
                                            alert('Failed to remove student');
                                          }
                                        }
                                      }}
                                      className="p-1.5 text-text-muted hover:text-rose-500 rounded-lg hover:bg-rose-500/10 transition-colors cursor-pointer"
                                      title="Remove Student"
                                    >
                                      <UserMinus size={16} />
                                    </button>
                                  )}
                                </td>
                              </tr>
                            ))
                          )}
                        </tbody>
                      </table>
                    </div>
                  </div>
                ) : activeTab === 'announcements' ? (
                  <div>
                    <div className="flex justify-between items-center mb-6">
                      <h3 className="text-lg font-black text-text uppercase tracking-tight">Announcements</h3>
                      <button onClick={() => setShowAnnouncementModal(true)} className="px-4 py-2 bg-primary text-white rounded-xl font-bold text-xs uppercase tracking-widest">Post Update</button>
                    </div>
                    <div className="space-y-4">
                      {announcements.length === 0 ? (
                        <p className="text-center text-text-muted text-sm py-8 font-medium">No announcements posted.</p>
                      ) : (
                        announcements.map(a => (
                          <div key={a.id} className="p-6 bg-muted/30 border border-border rounded-2xl">
                            <div className="flex justify-between items-start mb-2">
                              <h4 className="font-bold text-text">{a.title}</h4>
                              <span className="text-[0.6rem] text-text-muted dark:text-text-light font-black uppercase tracking-widest">{new Date(a.created_at).toLocaleDateString()}</span>
                            </div>
                            <p className="text-sm text-text-secondary">{a.content}</p>
                          </div>
                        ))
                      )}
                    </div>
                  </div>
                ) : activeTab === 'rollcall' ? (
                  <div>
                    <div className="flex justify-between items-center mb-6">
                      <h3 className="text-lg font-black text-text uppercase tracking-tight">Roll Call</h3>
                      <div className="flex gap-4 items-center">
                        <input type="date" value={attendanceDate} onChange={e => setAttendanceDate(e.target.value)} className="form-input bg-muted/50 border border-border rounded-xl px-4 py-2 text-sm font-bold text-text" />
                        <button onClick={handleSaveAttendance} className="px-4 py-2 bg-emerald-600 text-white rounded-xl font-bold text-xs uppercase tracking-widest">Save Roll Call</button>
                      </div>
                    </div>
                    <div className="overflow-x-auto">
                      <table className="w-full text-left">
                        <thead>
                          <tr className="bg-muted/50 border-b border-border">
                            <th className="px-6 py-4 text-[0.65rem] font-black text-primary uppercase tracking-widest">Student</th>
                            <th className="px-6 py-4 text-[0.65rem] font-black text-primary uppercase tracking-widest">Status</th>
                          </tr>
                        </thead>
                        <tbody className="divide-y divide-border">
                          {memberships.filter(m => m.status === 'active').length === 0 ? (
                            <tr><td colSpan={2} className="px-6 py-8 text-center text-text-muted text-sm font-medium">No active members to mark</td></tr>
                          ) : (
                            memberships.filter(m => m.status === 'active').map(m => (
                              <tr key={m.id} className="hover:bg-muted/30">
                                <td className="px-6 py-4">
                                  <p className="text-sm font-bold text-text">{m.first_name} {m.last_name}</p>
                                </td>
                                <td className="px-6 py-4">
                                  <div className="flex gap-2">
                                    {['present', 'absent', 'excused'].map(status => (
                                      <button
                                        key={status}
                                        onClick={() => setAttendanceData({...attendanceData, [m.student_id]: status})}
                                        className={`px-3 py-1.5 rounded-lg text-[0.6rem] font-black uppercase tracking-widest border transition-all ${
                                          attendanceData[m.student_id] === status 
                                            ? (status === 'present' 
                                                ? 'bg-emerald-500/10 text-emerald-600 border-emerald-500/30 dark:bg-emerald-950/30 dark:text-emerald-400 dark:border-emerald-900/50' 
                                                : status === 'absent' 
                                                  ? 'bg-rose-500/10 text-rose-600 border-rose-500/30 dark:bg-rose-950/30 dark:text-rose-400 dark:border-rose-900/50' 
                                                  : 'bg-orange-500/10 text-orange-600 border-orange-500/30 dark:bg-orange-950/30 dark:text-orange-400 dark:border-orange-900/50')
                                            : 'bg-card text-text-muted hover:bg-muted dark:hover:bg-muted/50 border-border'
                                        }`}
                                      >
                                        {status}
                                      </button>
                                    ))}
                                  </div>
                                </td>
                              </tr>
                            ))
                          )}
                        </tbody>
                      </table>
                    </div>
                  </div>
                ) : (
                  <ExtracurricularChat clubId={selectedClub.id} clubName={selectedClub.name} />
                )}
              </div>
            </div>
          )}
        </div>
      </div>
      )}

      {showClubModal && createPortal(
        <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-[150] flex items-center justify-center p-4" onClick={() => setShowClubModal(false)}>
          <div className="bg-card rounded-[2.5rem] w-full max-w-xl max-h-[90vh] flex flex-col shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200 border border-border" onClick={(e) => e.stopPropagation()}>
            <div className="px-10 py-8 bg-muted/50 border-b border-border flex justify-between items-center relative overflow-hidden flex-shrink-0">
              <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12 text-primary">
                <Trophy size={180} />
              </div>
              <div className="relative z-10">
                <h2 className="text-2xl font-black text-text tracking-tight uppercase">Create Activity</h2>
                <p className="text-xs font-bold text-text-muted uppercase tracking-widest mt-1">Configure new club or sport team</p>
              </div>
              <button onClick={() => setShowClubModal(false)} className="relative z-10 w-10 h-10 flex items-center justify-center rounded-xl bg-card border border-border text-text-muted hover:text-rose-500 transition-all shadow-sm">
                <X size={20} />
              </button>
            </div>
            <form onSubmit={handleSaveClub} className="p-10 space-y-6 overflow-y-auto flex-1">
              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Name</label>
                <input className="form-input text-text" value={clubForm.name} onChange={e => setClubForm({...clubForm, name: e.target.value})} placeholder="e.g. Chess Club" required />
              </div>
              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Teacher in Charge</label>
                <select
                  className="form-input text-text"
                  value={clubForm.teacher_in_charge_id || ''}
                  onChange={e => setClubForm({...clubForm, teacher_in_charge_id: e.target.value ? parseInt(e.target.value) : undefined})}
                  required
                >
                  <option value="">Select a teacher...</option>
                  {teachers.map(t => (
                    <option key={t.id} value={t.id}>{t.first_name} {t.last_name}</option>
                  ))}
                </select>
              </div>
              <div className="grid grid-cols-2 gap-6">
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Type</label>
                  <select className="form-input text-text" value={clubForm.type} onChange={e => setClubForm({...clubForm, type: e.target.value})}>
                    <option value="club">Club</option>
                    <option value="sport">Sport</option>
                  </select>
                </div>
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Schedule</label>
                  <input className="form-input text-text" value={clubForm.schedule} onChange={e => setClubForm({...clubForm, schedule: e.target.value})} placeholder="e.g. Wednesdays 14:00 - 15:00" />
                </div>
              </div>
              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Description</label>
                <textarea className="form-input text-text animate-none" value={clubForm.description} onChange={e => setClubForm({...clubForm, description: e.target.value})} rows={3} placeholder="Describe the activity..." />
              </div>
              <div className="flex gap-4 pt-4">
                <button type="button" onClick={() => setShowClubModal(false)} className="flex-1 py-4 bg-muted rounded-2xl text-xs font-black uppercase tracking-widest transition-all hover:bg-muted/80 text-text-muted">Cancel</button>
                <button type="submit" className="flex-1 py-4 bg-primary text-white rounded-2xl text-xs font-black uppercase tracking-widest transition-all shadow-lg shadow-primary/20 hover:bg-primary/90 flex items-center justify-center gap-2">
                  <CheckCircle2 size={16} /> Create Activity
                </button>
              </div>
            </form>
          </div>
        </div>
      ,
        document.body
      )}

      {showAnnouncementModal && createPortal(
        <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-[150] flex items-center justify-center p-4" onClick={() => setShowAnnouncementModal(false)}>
          <div className="bg-card rounded-[2.5rem] w-full max-w-xl max-h-[90vh] shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200 border border-border" onClick={(e) => e.stopPropagation()}>
            <div className="px-10 py-8 bg-muted/50 border-b border-border flex justify-between items-center relative overflow-hidden flex-shrink-0">
              <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12 text-primary">
                <Bell size={180} />
              </div>
              <div className="relative z-10">
                <h2 className="text-2xl font-black text-text tracking-tight uppercase">Post Announcement</h2>
                <p className="text-xs font-bold text-text-muted uppercase tracking-widest mt-1">Notification update to members</p>
              </div>
              <button onClick={() => setShowAnnouncementModal(false)} className="relative z-10 w-10 h-10 flex items-center justify-center rounded-xl bg-card border border-border text-text-muted hover:text-rose-500 transition-all shadow-sm">
                <X size={20} />
              </button>
            </div>
            <form onSubmit={handlePostAnnouncement} className="p-10 space-y-6 overflow-y-auto flex-1">
              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Title</label>
                <input className="form-input text-text" value={announcementForm.title} onChange={e => setAnnouncementForm({...announcementForm, title: e.target.value})} placeholder="e.g. Practice Cancelled Today" required />
              </div>
              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Content</label>
                <textarea className="form-input text-text animate-none" rows={4} value={announcementForm.content} onChange={e => setAnnouncementForm({...announcementForm, content: e.target.value})} placeholder="Write the announcement update details here..." required />
              </div>
              <div className="flex gap-4 pt-4">
                <button type="button" onClick={() => setShowAnnouncementModal(false)} className="flex-1 py-4 bg-muted rounded-2xl text-xs font-black uppercase tracking-widest transition-all hover:bg-muted/80 text-text-muted">Cancel</button>
                <button type="submit" className="flex-1 py-4 bg-primary text-white rounded-2xl text-xs font-black uppercase tracking-widest transition-all shadow-lg shadow-primary/20 hover:bg-primary/90 flex items-center justify-center gap-2">
                  <CheckCircle2 size={16} /> Notification Update
                </button>
              </div>
            </form>
          </div>
        </div>
      ,
        document.body
      )}

      {showEnrollModal && createPortal(
        <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-[150] flex items-center justify-center p-4" onClick={() => setShowEnrollModal(false)}>
          <div className="bg-card rounded-[2.5rem] w-full max-w-xl max-h-[90vh] shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200 border border-border" onClick={(e) => e.stopPropagation()}>
            <div className="px-10 py-8 bg-muted/50 border-b border-border flex justify-between items-center relative overflow-hidden flex-shrink-0">
              <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12 text-primary">
                <Users size={180} />
              </div>
              <div className="relative z-10">
                <h2 className="text-2xl font-black text-text tracking-tight uppercase">Add Student</h2>
                <p className="text-xs font-bold text-text-muted uppercase tracking-widest mt-1">Enroll student into {selectedClub?.name}</p>
              </div>
              <button onClick={() => { setShowEnrollModal(false); setSelectedStudentId(''); }} className="relative z-10 w-10 h-10 flex items-center justify-center rounded-xl bg-card border border-border text-text-muted hover:text-rose-500 transition-all shadow-sm">
                <X size={20} />
              </button>
            </div>
            <div className="p-10 space-y-6 overflow-y-auto flex-1">
              <div className="space-y-1.5 relative" ref={dropdownRef}>
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Select Student</label>

                {/* Searchable input */}
                <div className="relative group">
                  <Search size={18} className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted group-focus-within:text-primary transition-colors" />
                  <input
                    type="text"
                    className="form-input pl-11 text-text pr-10 cursor-pointer"
                    placeholder="Type name or email to search..."
                    value={studentSearch}
                    onChange={e => {
                      setStudentSearch(e.target.value);
                      setShowDropdown(true);
                      if (selectedStudentId) {
                        setSelectedStudentId('');
                      }
                    }}
                    onFocus={() => {
                      setShowDropdown(true);
                      if (!selectedStudentId) {
                        setStudentSearch('');
                      }
                    }}
                  />
                  {selectedStudentId && (
                    <button
                      type="button"
                      onClick={() => {
                        setSelectedStudentId('');
                        setStudentSearch('');
                        setShowDropdown(true);
                      }}
                      className="absolute right-4 top-1/2 -translate-y-1/2 text-text-muted hover:text-rose-500"
                    >
                      <X size={16} />
                    </button>
                  )}
                </div>

                {/* Dropdown Options List */}
                {showDropdown && (
                  <div className="absolute z-[160] left-0 right-0 mt-1 max-h-60 overflow-y-auto bg-card border border-border rounded-2xl shadow-xl animate-in fade-in slide-in-from-top-2 duration-200">
                    {filteredStudents.length === 0 ? (
                      <div className="p-4 text-center text-text-muted text-xs font-bold uppercase tracking-widest">
                        No students found
                      </div>
                    ) : (
                      filteredStudents.map(s => (
                        <div
                          key={s.id}
                          onClick={() => {
                            setSelectedStudentId(String(s.id));
                            setStudentSearch(`${s.first_name} ${s.last_name}`);
                            setShowDropdown(false);
                          }}
                          className={`px-4 py-3 cursor-pointer text-sm font-bold text-text hover:bg-primary/5 transition-colors border-b border-border/50 last:border-0 flex flex-col ${selectedStudentId === String(s.id) ? 'bg-primary/5 text-primary' : ''}`}
                        >
                          <span>{s.first_name} {s.last_name}</span>
                          <span className="text-[0.65rem] text-text-muted dark:text-text-secondary font-medium mt-0.5">{s.email}</span>
                        </div>
                      ))
                    )}
                  </div>
                )}
              </div>
              <div className="flex gap-4 pt-4">
                <button onClick={() => { setShowEnrollModal(false); setSelectedStudentId(''); }} className="flex-1 py-4 bg-muted rounded-2xl text-xs font-black uppercase tracking-widest transition-all hover:bg-muted/80 text-text-muted">Cancel</button>
                <button
                  onClick={async () => {
                    if (!selectedStudentId || !selectedClub) return;
                    setEnrollSubmitting(true);
                    try {
                      await joinClub(selectedClub.id, parseInt(selectedStudentId));
                      await fetchMemberships(selectedClub.id);
                      setShowEnrollModal(false);
                      setSelectedStudentId('');
                    } catch (err) {
                      alert('Failed to add student to activity');
                    } finally {
                      setEnrollSubmitting(false);
                    }
                  }}
                  disabled={enrollSubmitting || !selectedStudentId}
                  className="flex-1 py-4 bg-primary text-white rounded-2xl text-xs font-black uppercase tracking-widest transition-all shadow-lg shadow-primary/20 hover:bg-primary/90 flex items-center justify-center gap-2 active:scale-95 disabled:opacity-50"
                >
                  {enrollSubmitting ? 'Enrolling...' : 'Confirm Enrollment'}
                </button>
              </div>
            </div>
          </div>
        </div>
      ,
        document.body
      )}

      {showEditModal && createPortal(
        <div className="fixed inset-0 bg-[#002147]/80 backdrop-blur-md z-[150] flex items-center justify-center p-3 sm:p-6 overflow-y-auto" onClick={() => setShowEditModal(false)}>
          <div className="bg-card rounded-[2.5rem] w-full max-w-xl max-h-[92vh] shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200 border border-border flex flex-col my-auto" onClick={(e) => e.stopPropagation()}>
            <div className="px-6 sm:px-10 py-6 sm:py-8 bg-muted/50 border-b border-border flex justify-between items-center relative overflow-hidden shrink-0">
              <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12 text-primary pointer-events-none">
                <Edit2 size={180} />
              </div>
              <div className="relative z-10 min-w-0 flex-1 pr-2">
                <h2 className="text-xl sm:text-2xl font-black text-text tracking-tight uppercase truncate">Edit Activity</h2>
                <p className="text-xs font-bold text-text-muted uppercase tracking-widest mt-1 truncate">Modify activity configuration</p>
              </div>
              <button onClick={() => setShowEditModal(false)} className="relative z-10 w-10 h-10 flex items-center justify-center rounded-xl bg-card border border-border text-text-muted hover:text-rose-500 transition-all shadow-sm shrink-0 cursor-pointer">
                <X size={20} />
              </button>
            </div>
            <div className="p-4 sm:p-8 md:p-10 space-y-4 sm:space-y-6 overflow-y-auto flex-1 custom-scrollbar text-left">
              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Name</label>
                <input className="form-input text-text" value={editForm.name} onChange={e => setEditForm({...editForm, name: e.target.value})} placeholder="e.g. Chess Club" required />
              </div>
              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Teacher in Charge</label>
                <select 
                  className="form-input text-text" 
                  value={editForm.teacher_in_charge_id || ''} 
                  onChange={e => setEditForm({...editForm, teacher_in_charge_id: e.target.value ? parseInt(e.target.value) : undefined})}
                  required
                >
                  <option value="">Select a teacher...</option>
                  {teachers.map(t => (
                    <option key={t.id} value={t.id}>{t.first_name} {t.last_name}</option>
                  ))}
                </select>
              </div>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-6">
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Type</label>
                  <select className="form-input text-text" value={editForm.type} onChange={e => setEditForm({...editForm, type: e.target.value as 'club' | 'sport'})}>
                    <option value="club">Club</option>
                    <option value="sport">Sport</option>
                  </select>
                </div>
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Schedule</label>
                  <input className="form-input text-text" value={editForm.schedule} onChange={e => setEditForm({...editForm, schedule: e.target.value})} placeholder="e.g. Wednesdays 14:00 - 15:00" />
                </div>
              </div>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-6">
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Max Members (Capacity)</label>
                  <input type="number" className="form-input text-text" value={editForm.max_members || ''} onChange={e => setEditForm({...editForm, max_members: parseInt(e.target.value) || 0})} placeholder="Unlimited" />
                </div>
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Status</label>
                  <select className="form-input text-text" value={editForm.status} onChange={e => setEditForm({...editForm, status: e.target.value as 'active' | 'inactive'})}>
                    <option value="active">Active</option>
                    <option value="inactive">Inactive</option>
                  </select>
                </div>
              </div>
              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Description</label>
                <textarea className="form-input text-text animate-none" value={editForm.description} onChange={e => setEditForm({...editForm, description: e.target.value})} rows={3} placeholder="Describe the activity..." />
              </div>
              <div className="flex flex-col sm:flex-row gap-3 sm:gap-4 pt-4">
                <button onClick={() => setShowEditModal(false)} className="w-full sm:flex-1 py-3.5 sm:py-4 bg-muted rounded-2xl text-xs font-black uppercase tracking-widest transition-all hover:bg-muted/80 text-text-muted cursor-pointer">Cancel</button>
                <button 
                  onClick={handleSaveEdit} 
                  disabled={editSubmitting || !editForm.name}
                  className="w-full sm:flex-1 py-3.5 sm:py-4 bg-primary text-white rounded-2xl text-xs font-black uppercase tracking-widest transition-all shadow-lg shadow-primary/20 hover:bg-primary/90 flex items-center justify-center gap-2 active:scale-95 cursor-pointer"
                >
                  <span>{editSubmitting ? 'Saving...' : 'Save Changes'}</span>
                </button>
              </div>
            </div>
          </div>
        </div>
      ,
        document.body
      )}
    </div>
  );
}
