import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Search, Plus, Filter, Users, BookOpen, GraduationCap } from 'lucide-react';
import { useCohortsStore, SUPPORTED_PROGRAMMES, Cohort } from '../../store/cohorts';
import { useAuthStore } from '../../store/auth';
import RoleBadge from '../../components/RoleBadge';

const PROGRAMME_BADGE: Record<string, string> = {
  zimsec: 'bg-amber-500 text-white',
  igcse: 'bg-blue-500 text-white',
  as: 'bg-emerald-500 text-white',
  a2: 'bg-violet-500 text-white',
  primary: 'bg-pink-500 text-white',
  other: 'bg-zinc-500 text-white',
};

export default function Cohorts() {
  const navigate = useNavigate();
  const { user } = useAuthStore();
  const { cohorts, loading, error, fetchCohorts } = useCohortsStore((s) => ({
    cohorts: s.cohorts,
    loading: s.loading,
    error: s.error,
    fetchCohorts: s.fetchCohorts,
  }));

  const [search, setSearch] = useState('');
  const [programmeFilter, setProgrammeFilter] = useState<string>('');
  const [yearFilter, setYearFilter] = useState<string>('');

  useEffect(() => {
    fetchCohorts({
      programme: programmeFilter || undefined,
      academic_year: yearFilter || undefined,
      search: search || undefined,
    });
  }, [programmeFilter, yearFilter, search, fetchCohorts]);

  const canManage = user?.role === 'school_admin' || user?.role === 'systems_admin';

  return (
    <div className="space-y-6 animate-in fade-in duration-500">
      <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-3">
        <div>
          <h1 className="text-3xl font-black text-text tracking-tight">Student Cohorts</h1>
          <p className="text-sm text-text-muted mt-1">
            ZIMSEC, IGCSE, AS, A2 — and any other academic programme grouping.
          </p>
        </div>
        {canManage && (
          <button
            onClick={() => navigate('/admin/cohorts/new')}
            className="inline-flex items-center gap-1.5 px-4 py-2 rounded-xl text-sm font-bold bg-primary text-white shadow-lg shadow-primary/20 hover:opacity-95"
          >
            <Plus size={14} /> New Cohort
          </button>
        )}
      </div>

      {/* Filter bar */}
      <div className="bg-card border border-border rounded-2xl p-4 flex flex-col md:flex-row gap-3">
        <div className="flex-1 relative">
          <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted" />
          <input
            type="text"
            placeholder="Search by name or description…"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full pl-9 pr-3 py-2 rounded-xl border border-border bg-background text-text text-sm"
          />
        </div>
        <select
          // NFR6 fix: bare <select> with no associated <label> is
          // flagged as critical by axe (select-name). Wrap the
          // visible UI in a labelled group.
          aria-label="Filter by programme"
          value={programmeFilter}
          onChange={(e) => setProgrammeFilter(e.target.value)}
          className="px-3 py-2 rounded-xl border border-border bg-background text-text text-sm"
        >
          <option value="">All programmes</option>
          {SUPPORTED_PROGRAMMES.map((p) => (
            <option key={p.value} value={p.value}>{p.label}</option>
          ))}
        </select>
        <input
          type="text"
          placeholder="Academic year…"
          value={yearFilter}
          onChange={(e) => setYearFilter(e.target.value)}
          className="w-32 px-3 py-2 rounded-xl border border-border bg-background text-text text-sm"
        />
      </div>

      {error && (
        <div className="bg-rose-500/10 border border-rose-500/30 text-rose-500 rounded-xl px-4 py-3 text-sm">{error}</div>
      )}

      {loading ? (
        <div className="text-center text-text-muted py-12">Loading…</div>
      ) : cohorts.length === 0 ? (
        <div className="text-center text-text-muted py-12">
          No cohorts match. {canManage && <span>Click <strong>New Cohort</strong> to create one.</span>}
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {cohorts.map((c) => (
            <CohortCard key={c.id} cohort={c} onOpen={() => navigate(`/admin/cohorts/${c.id}`)} />
          ))}
        </div>
      )}
    </div>
  );
}

function CohortCard({ cohort, onOpen }: { cohort: Cohort; onOpen: () => void }) {
  return (
    <button
      onClick={onOpen}
      className="text-left bg-card border border-border rounded-2xl p-5 hover:shadow-md hover:border-primary/50 transition-all group"
    >
      <div className="flex items-start justify-between gap-2 mb-3">
        <div className="min-w-0 flex-1">
          <div className="text-xs font-black uppercase tracking-wider text-text-muted mb-1">
            {cohort.level || '—'} · {cohort.academic_year || 'no year'}
          </div>
          <h3 className="text-lg font-black text-text truncate">{cohort.name}</h3>
        </div>
        <span
          className={`px-2 py-1 rounded-full text-[0.65rem] font-black uppercase tracking-wider ${PROGRAMME_BADGE[cohort.programme] || 'bg-zinc-500 text-white'}`}
        >
          {cohort.programme}
        </span>
      </div>
      {cohort.description && (
        <p className="text-xs text-text-muted mb-3 line-clamp-2">{cohort.description}</p>
      )}
      <div className="flex items-center gap-4 text-xs text-text-secondary">
        <span className="inline-flex items-center gap-1">
          <Users size={12} /> {cohort.student_count ?? 0}
        </span>
        <span className="inline-flex items-center gap-1">
          <BookOpen size={12} /> {cohort.class_count ?? 0}
        </span>
        <span className="inline-flex items-center gap-1">
          <GraduationCap size={12} /> {cohort.exam_group_count ?? 0}
        </span>
        {!cohort.is_active && (
          <span className="px-2 py-0.5 rounded-full text-[0.6rem] font-bold uppercase bg-zinc-500/20 text-text-muted ml-auto">
            inactive
          </span>
        )}
      </div>
    </button>
  );
}
