import { useEffect, useState } from 'react';
import { useClubsStore, Club } from '../../store/clubs';
import { useAuthStore } from '../../store/auth';
import { 
  Trophy, Users, Calendar, Search, 
  ChevronRight, CheckCircle2, UserPlus, LogOut,
  Bell, Info, Clock, Activity, Medal, MessageSquare, Gamepad2, ArrowLeft,
  Play
} from 'lucide-react';
import ExtracurricularChat from '../../components/ExtracurricularChat';
import EdutainmentGames from '../../components/EdutainmentGames';

export default function StudentExtracurriculars() {
  const { user } = useAuthStore();
  const { 
    clubs, memberships, announcements, loading,
    fetchClubs, fetchMemberships, fetchAnnouncements,
    joinClub, leaveClub
  } = useClubsStore();

  const [activeTab, setActiveTab] = useState('discover'); // discover, my_clubs, announcements
  const [search, setSearch] = useState('');
  const [filterType, setFilterType] = useState('all'); // all, sport, club
  const [selectedMyClub, setSelectedMyClub] = useState<any | null>(null);
  const [myClubTab, setMyClubTab] = useState('chat'); // chat, announcements, games

  useEffect(() => {
    fetchClubs();
    if (user?.id) {
      fetchMemberships(undefined, user.id);
      fetchAnnouncements();
    }
  }, [user]);

  const filteredClubs = clubs.filter(c => 
    (filterType === 'all' || c.type === filterType) &&
    (c.name.toLowerCase().includes(search.toLowerCase()) || c.description?.toLowerCase().includes(search.toLowerCase()))
  );

  const myActiveClubs = memberships.filter(m => m.status === 'active').map(m => m.club_id);

  return (
    <div className="space-y-10 animate-in fade-in duration-700 pb-10">
      {/* Header */}
      <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">Extracurriculars</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>Student Life</span>
            <ChevronRight size={12} className="text-text-muted/30" />
            <span className="text-primary">Sports & Clubs</span>
          </nav>
        </div>
      </div>

      {/* Featured Edutainment Banner */}
      {activeTab !== 'games' && (
        <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">
                Test your skills, boost your grades, and challenge your brain! Solve equations in Math Sprint, unscramble terms in Word Scramble, or ace the Academia Trivia.
              </p>
            </div>
          </div>
          <button 
            onClick={() => setActiveTab('games')}
            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>
      )}

      {/* Control Bar */}
      <div className="bg-card border border-border rounded-[2rem] 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: 'discover', label: 'Discover', icon: Trophy },
            { id: 'my_clubs', label: 'My Activities', icon: Activity },
            { id: 'games', label: 'Games Arena', icon: Gamepad2 },
            { id: 'announcements', label: 'Announcements', icon: Bell },
          ].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>

        {activeTab === 'discover' && (
          <>
            <div className="relative group flex-1">
              <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="w-full bg-muted/50 border border-border rounded-2xl pl-11 pr-4 py-3.5 text-sm font-medium focus:outline-none focus:ring-4 focus:ring-primary/5 focus:bg-card focus:border-primary transition-all text-text"
                placeholder="Search activities..."
                value={search}
                onChange={e => setSearch(e.target.value)}
              />
            </div>
            <select 
              className="px-5 py-3 bg-muted/50 text-text-muted dark:text-text-secondary rounded-2xl border border-border text-[0.7rem] font-black uppercase tracking-widest outline-none"
              value={filterType}
              onChange={e => setFilterType(e.target.value)}
            >
              <option value="all">All Types</option>
              <option value="sport">Sports</option>
              <option value="club">Clubs & Societies</option>
            </select>
          </>
        )}
      </div>

      {/* Main Content */}
      <div className="min-h-[400px]">
        {loading ? (
          <div className="py-20 text-center">
            <div className="w-12 h-12 border-4 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
            <p className="text-text-muted font-bold uppercase tracking-widest text-xs italic">Loading activities...</p>
          </div>
        ) : activeTab === 'discover' ? (
          <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
            {filteredClubs.map(c => (
              <div key={c.id} className="bg-card border border-border rounded-[2.5rem] p-8 hover:shadow-xl transition-all group flex flex-col relative overflow-hidden">
                <div className="absolute top-0 right-0 w-32 h-32 bg-primary/5 rounded-bl-[4rem] -z-10 group-hover:scale-110 transition-transform"></div>
                <div className="flex justify-between items-start mb-6">
                  <div className={`w-14 h-14 rounded-2xl flex items-center justify-center text-white font-black shadow-lg ${c.type === 'sport' ? 'bg-orange-500 shadow-orange-500/20' : 'bg-blue-600 shadow-blue-600/20'}`}>
                    {c.type === 'sport' ? <Medal size={24} /> : <Users size={24} />}
                  </div>
                  <span className={`px-3 py-1 rounded-lg text-[0.6rem] font-black uppercase tracking-widest border ${
                    myActiveClubs.includes(c.id) ? 'bg-emerald-50 text-emerald-600 border-emerald-100 dark:bg-emerald-950/30 dark:text-emerald-400 dark:border-emerald-900/50' : 'bg-muted text-text-muted dark:text-text-secondary border-border'
                  }`}>
                    {myActiveClubs.includes(c.id) ? 'Enrolled' : 'Available'}
                  </span>
                </div>
                
                <div className="space-y-2 mb-6 flex-grow">
                  <h3 className="text-xl font-black text-text tracking-tight">{c.name}</h3>
                  <p className="text-[0.8rem] text-text-muted dark:text-text-secondary font-medium line-clamp-2">{c.description}</p>
                </div>

                <div className="space-y-3 pt-6 border-t border-border">
                    <div className="flex items-center gap-3 text-[0.7rem] font-black uppercase tracking-widest text-text-muted dark:text-text-light">
                        <Clock size={14} className="text-primary" /> {c.schedule || 'TBA'}
                    </div>
                    <div className="flex justify-between items-center text-[0.7rem] font-black uppercase tracking-widest text-text-muted dark:text-text-light">
                        <span className="flex items-center gap-2"><Users size={14} className="text-primary" /> {c.current_members || 0} {c.max_members ? `/ ${c.max_members}` : ''} Members</span>
                    </div>
                </div>

                <div className="mt-6">
                  {myActiveClubs.includes(c.id) ? (
                    <button onClick={() => leaveClub(c.id, user?.id)} className="w-full py-3 bg-rose-50 hover:bg-rose-100 text-rose-600 dark:bg-rose-950/20 dark:hover:bg-rose-950/35 dark:text-rose-400 rounded-xl font-black text-[0.65rem] uppercase tracking-widest transition-all flex items-center justify-center gap-2">
                        <LogOut size={16} /> Leave Activity
                    </button>
                  ) : (
                    <button 
                        onClick={() => joinClub(c.id, user?.id)} 
                        disabled={c.max_members !== null && (c.current_members || 0) >= c.max_members}
                        className="w-full py-3 bg-primary text-white rounded-xl font-black text-[0.65rem] uppercase tracking-widest hover:bg-primary/90 transition-all shadow-lg active:scale-95 flex items-center justify-center gap-2 disabled:opacity-50 disabled:grayscale"
                    >
                        <UserPlus size={16} /> {c.max_members !== null && (c.current_members || 0) >= c.max_members ? 'Capacity Reached' : 'Join Activity'}
                    </button>
                  )}
                </div>
              </div>
            ))}
          </div>
        ) : activeTab === 'my_clubs' ? (
          <div>
            {selectedMyClub ? (
              <div className="space-y-6">
                {/* Back Button and Activity Header */}
                <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">
                  <div className="flex items-center gap-4">
                    <button 
                      onClick={() => setSelectedMyClub(null)} 
                      className="p-3 text-text-muted hover:text-primary bg-muted/50 hover:bg-muted rounded-2xl transition-all"
                      title="Back to Activities"
                    >
                      <ArrowLeft size={18} />
                    </button>
                    <div>
                      <div className="flex items-center gap-2">
                        <h3 className="text-2xl font-black text-text tracking-tight uppercase">{selectedMyClub.club_name}</h3>
                        <span className={`px-2.5 py-0.5 rounded-md text-[0.6rem] font-black uppercase tracking-widest border ${
                          selectedMyClub.club_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'
                        }`}>
                          {selectedMyClub.club_type}
                        </span>
                      </div>
                      <p className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted dark:text-text-light mt-1">Role: {selectedMyClub.role} • Joined {new Date(selectedMyClub.join_date).toLocaleDateString()}</p>
                    </div>
                  </div>
                  <button 
                    onClick={() => {
                      leaveClub(selectedMyClub.club_id, user?.id);
                      setSelectedMyClub(null);
                    }} 
                    className="px-5 py-2.5 bg-rose-50 hover:bg-rose-100 text-rose-600 border border-rose-100 dark:bg-rose-950/20 dark:hover:bg-rose-950/35 dark:text-rose-400 dark:border-rose-900/50 rounded-xl font-black text-[0.65rem] uppercase tracking-widest transition-all flex items-center justify-center gap-2"
                  >
                    <LogOut size={14} /> Leave Activity
                  </button>
                </div>

                {/* Sub-tabs for Activity Hub */}
                <div className="bg-card border border-border rounded-[2rem] 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">
                    {[
                      { id: 'chat', label: 'Chat Room', icon: MessageSquare },
                      { id: 'announcements', label: 'Announcements', icon: Bell },
                      { id: 'games', label: 'Edutainment Games', icon: Gamepad2 },
                    ].map((tab) => (
                      <button
                        key={tab.id}
                        onClick={() => setMyClubTab(tab.id)}
                        className={`
                          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
                          ${myClubTab === 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>

                {/* Sub-tab Content */}
                <div className="animate-in fade-in duration-300">
                  {myClubTab === 'chat' && (
                    <ExtracurricularChat clubId={selectedMyClub.club_id} clubName={selectedMyClub.club_name} />
                  )}
                  
                  {myClubTab === 'announcements' && (
                    <div className="space-y-6">
                      {announcements.filter(a => a.club_id === selectedMyClub.club_id).length === 0 ? (
                        <div className="py-20 text-center bg-card border-2 border-dashed border-border rounded-[3rem]">
                          <Bell size={48} className="mx-auto text-text-muted/30 mb-4" />
                          <h4 className="text-lg font-black text-text mb-1 uppercase tracking-tight">No Announcements</h4>
                          <p className="text-xs text-text-muted max-w-xs mx-auto">There are no announcements for this activity yet.</p>
                        </div>
                      ) : (
                        announcements.filter(a => a.club_id === selectedMyClub.club_id).map(a => (
                          <div key={a.id} className="bg-card border border-border rounded-[2.5rem] p-8 shadow-sm">
                            <div className="flex justify-between items-start mb-4">
                              <h4 className="text-xl font-black text-text tracking-tight">{a.title}</h4>
                              <span className="text-[0.6rem] font-bold text-text-muted dark:text-text-light uppercase tracking-widest">{new Date(a.created_at).toLocaleDateString()}</span>
                            </div>
                            <p className="text-sm font-medium text-text-secondary leading-relaxed whitespace-pre-wrap">{a.content}</p>
                            <p className="text-[0.65rem] font-black text-text-muted uppercase tracking-widest mt-6 pt-6 border-t border-border">Posted by: {a.author_name}</p>
                          </div>
                        ))
                      )}
                    </div>
                  )}

                  {myClubTab === 'games' && (
                    <EdutainmentGames onClose={() => setSelectedMyClub(null)} activityName={selectedMyClub.club_name} />
                  )}
                </div>
              </div>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                {memberships.filter(m => m.status === 'active').length === 0 ? (
                  <div className="col-span-full py-24 text-center bg-card border-2 border-dashed border-border rounded-[3rem]">
                    <Activity size={64} className="mx-auto text-text-muted/30 mb-6" />
                    <h3 className="text-2xl font-black text-text mb-2 uppercase tracking-tighter">No Active Enrollments</h3>
                    <p className="text-text-muted font-medium max-w-sm mx-auto">You haven't joined any clubs or sports yet. Head over to the Discover tab to find activities.</p>
                  </div>
                ) : (
                  memberships.filter(m => m.status === 'active').map(m => (
                    <div 
                      key={m.id} 
                      onClick={() => { setSelectedMyClub(m); setMyClubTab('chat'); }}
                      className="bg-card border border-border hover:border-primary/30 rounded-[2.5rem] p-8 shadow-sm flex items-center justify-between cursor-pointer hover:shadow-md transition-all group"
                    >
                      <div className="flex items-center gap-6">
                        <div className={`w-14 h-14 rounded-2xl flex items-center justify-center text-white font-black shadow-lg ${m.club_type === 'sport' ? 'bg-orange-500 shadow-orange-500/20' : 'bg-blue-600 shadow-blue-600/20'} group-hover:scale-105 transition-transform`}>
                          {m.club_type === 'sport' ? <Medal size={24} /> : <Users size={24} />}
                        </div>
                        <div>
                          <h4 className="text-lg font-black text-text tracking-tight group-hover:text-primary transition-colors">{m.club_name}</h4>
                          <p className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted dark:text-text-light mt-1">Role: {m.role} • Joined: {new Date(m.join_date).toLocaleDateString()}</p>
                          <span className="text-[0.55rem] font-black uppercase tracking-widest text-primary mt-2 inline-flex items-center gap-1.5 bg-primary/5 px-2 py-0.5 rounded">
                            <MessageSquare size={10} /> Enter Activity Hub
                          </span>
                        </div>
                      </div>
                      <button 
                        onClick={(e) => {
                          e.stopPropagation();
                          leaveClub(m.club_id, user?.id);
                        }} 
                        className="p-3 text-rose-500 bg-rose-50 hover:bg-rose-100 dark:bg-rose-950/20 dark:hover:bg-rose-950/35 dark:text-rose-400 rounded-xl transition-all"
                        title="Leave Activity"
                      >
                        <LogOut size={18} />
                      </button>
                    </div>
                  ))
                )}
              </div>
            )}
          </div>
        ) : activeTab === 'games' ? (
          <EdutainmentGames onClose={() => setActiveTab('discover')} />
        ) : (
          <div className="space-y-6">
             {announcements.length === 0 ? (
                 <div className="py-24 text-center bg-card border-2 border-dashed border-border rounded-[3rem]">
                    <Bell size={64} className="mx-auto text-text-muted/30 mb-6" />
                    <h3 className="text-2xl font-black text-text mb-2 uppercase tracking-tighter">No Announcements</h3>
                    <p className="text-text-muted font-medium max-w-sm mx-auto">There are no recent announcements for your enrolled clubs and sports.</p>
                </div>
             ) : (
                 announcements.map(a => (
                     <div key={a.id} className="bg-card border border-border rounded-[2.5rem] p-8 shadow-sm">
                         <div className="flex justify-between items-start mb-4">
                             <div>
                                <span className="inline-block px-3 py-1 bg-primary/10 text-primary rounded-lg text-[0.6rem] font-black uppercase tracking-widest mb-3">
                                    {a.club_name}
                                </span>
                                <h4 className="text-xl font-black text-text tracking-tight">{a.title}</h4>
                             </div>
                             <span className="text-[0.6rem] font-bold text-text-muted dark:text-text-light uppercase tracking-widest">{new Date(a.created_at).toLocaleDateString()}</span>
                         </div>
                         <p className="text-sm font-medium text-text-secondary leading-relaxed whitespace-pre-wrap">{a.content}</p>
                         <p className="text-[0.65rem] font-black text-text-muted uppercase tracking-widest mt-6 pt-6 border-t border-border">Posted by: {a.author_name}</p>
                     </div>
                 ))
             )}
          </div>
        )}
      </div>
    </div>
  );
}
