import { useState, useEffect } from 'react';
import { Trophy, Users, Calendar, AlertCircle, Plus, Search, Shield, ChevronRight } from 'lucide-react';
import { Link } from 'react-router-dom';
import api from '../../store/auth';

export default function ClubsHeadDashboard() {
  const [stats, setStats] = useState({
    totalClubs: 0,
    totalMembers: 0,
    activeEvents: 0
  });
  const [recentClubs, setRecentClubs] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchDashboardData = async () => {
      try {
        setLoading(true);
        const clubsResponse = await api.get('/clubs');
        const clubs = clubsResponse.data;
        
        let activeEventsCount = 0;
        try {
          const eventsResponse = await api.get('/calendar');
          const events = eventsResponse.data || [];
          activeEventsCount = events.filter((e: any) => 
            e.event_type === 'club' || 
            e.event_type === 'sports' || 
            e.event_type === 'activity' ||
            (e.description && e.description.toLowerCase().includes('club'))
          ).length;
        } catch (e) {
          console.error('Failed to load active events for clubs', e);
        }

        setStats({
          totalClubs: clubs.length,
          totalMembers: clubs.reduce((acc: number, club: any) => acc + (club.current_members || 0), 0),
          activeEvents: activeEventsCount
        });
        
        setRecentClubs(clubs.slice(0, 5));
      } catch (error) {
        console.error('Error fetching club data:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchDashboardData();
  }, []);

  const statCards = [
    { label: 'Active Clubs & Sports', value: stats.totalClubs, icon: Trophy, color: 'blue' },
    { label: 'Total Enrolled Members', value: stats.totalMembers, icon: Users, color: 'emerald' },
    { label: 'Upcoming Events', value: stats.activeEvents, icon: Calendar, color: 'purple' },
  ];

  return (
    <div className="p-6">
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-8">
        <div>
          <h1 className="text-2xl font-bold text-text flex items-center gap-2">
            <Shield className="text-primary" />
            Clubs Head Dashboard
          </h1>
          <p className="text-text-muted text-sm mt-1">Manage all school clubs, sports teams, and activities</p>
        </div>
        <div className="flex gap-3">
          <Link
            to="/clubs-management"
            className="flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-lg hover:opacity-90 transition-all shadow-sm font-semibold"
          >
            <Trophy size={20} />
            Manage Clubs
          </Link>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
        {statCards.map((s, i) => (
          <div key={i} className="bg-surface p-6 rounded-xl border border-border shadow-sm flex items-center gap-4">
            <div className={`w-14 h-14 rounded-xl bg-${s.color}-50 dark:bg-${s.color}-900/20 text-${s.color}-600 dark:text-${s.color}-400 flex items-center justify-center flex-shrink-0`}>
              <s.icon size={28} />
            </div>
            <div>
              <p className="text-sm text-text-muted font-medium mb-1">{s.label}</p>
              <h3 className="text-3xl font-black text-text leading-none">{loading ? '-' : s.value}</h3>
            </div>
          </div>
        ))}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
        <div className="ng-table-container">
          <div className="px-6 py-4 border-b border-border flex items-center justify-between">
            <h3 className="font-bold text-text flex items-center gap-2">
              <Trophy size={18} className="text-primary" />
              Active Clubs Overview
            </h3>
            <Link to="/clubs-management" className="text-primary text-sm font-semibold hover:underline">View All</Link>
          </div>
          <table className="ng-table">
            <thead className="ng-table-header">
              <tr>
                <th>Club Name</th>
                <th>Category</th>
                <th className="text-right">Members</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border/50 text-sm">
              {loading ? (
                <tr><td colSpan={3} className="p-8 text-center text-text-muted">Loading clubs...</td></tr>
              ) : recentClubs.length === 0 ? (
                <tr><td colSpan={3} className="p-8 text-center text-text-muted">No active clubs found.</td></tr>
              ) : (
                recentClubs.map(club => (
                  <tr key={club.id} className="ng-table-row">
                    <td className="ng-table-cell font-bold text-text">{club.name}</td>
                    <td className="ng-table-cell">
                      <span className="inline-flex items-center px-2 py-0.5 rounded bg-background-alt text-text-secondary text-[0.65rem] font-bold uppercase border border-border">
                        {club.type}
                      </span>
                    </td>
                    <td className="ng-table-cell text-right font-black text-primary">
                      {club.current_members || 0}
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        <div className="bg-surface rounded-xl border border-border shadow-sm p-6 flex flex-col items-center justify-center text-center">
          <div className="w-16 h-16 bg-primary-50 dark:bg-primary-900/20 text-primary rounded-full flex items-center justify-center mb-4">
            <Calendar size={32} />
          </div>
          <h3 className="text-lg font-bold text-text mb-2">Activities Calendar</h3>
          <p className="text-sm text-text-muted mb-6 max-w-sm">Keep track of all upcoming club events, matches, and meetings across the school.</p>
          <Link to="/notice-board" className="px-6 py-2 bg-background-alt border border-border text-text-secondary rounded-lg hover:bg-background-alt/80 transition-colors font-semibold flex items-center gap-2">
            View Announcements <ChevronRight size={16} />
          </Link>
        </div>
      </div>
    </div>
  );
}
