import React, { useEffect, useState } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { ArrowLeft, Users, BookOpen, GraduationCap, Plus, Trash2, X, Loader2, Edit3 } from 'lucide-react';
import api from '../../store/api';
import { useCohortsStore, CohortDetail as CohortDetailT } from '../../store/cohorts';
import { useAuthStore } from '../../store/auth';

export default function CohortDetailPage() {
  const { id } = useParams<{ id: string }>();
  const cohortId = Number(id);
  const navigate = useNavigate();
  const { user } = useAuthStore();
  const { detailById, loading, error, fetchCohort } = useCohortsStore((s) => ({
    detailById: s.detailById,
    loading: s.loading,
    error: s.error,
    fetchCohort: s.fetchCohort,
  }));

  const [tab, setTab] = useState<'overview' | 'students' | 'classes' | 'exam-groups'>('overview');
  const [showAddStudents, setShowAddStudents] = useState(false);
  const [showLinkClass, setShowLinkClass] = useState(false);
  const [showLinkExamGroup, setShowLinkExamGroup] = useState(false);

  useEffect(() => {
    if (cohortId) fetchCohort(cohortId);
  }, [cohortId, fetchCohort]);

  const cohort = detailById[cohortId];
  const canManage = user?.role === 'school_admin' || user?.role === 'systems_admin';

  if (loading && !cohort) {
    return <div className="text-center text-text-muted py-12">Loading…</div>;
  }
  if (error) {
    return <div className="bg-rose-500/10 border border-rose-500/30 text-rose-500 rounded-xl px-4 py-3 text-sm">{error}</div>;
  }
  if (!cohort) {
    return <div className="text-center text-text-muted py-12">Cohort not found.</div>;
  }

  return (
    <div className="space-y-6 animate-in fade-in duration-500">
      <div className="flex items-center gap-3">
        <button onClick={() => navigate('/admin/cohorts')} className="p-2 rounded-lg hover:bg-background-alt" title="Back">
          <ArrowLeft size={18} />
        </button>
        <div className="flex-1 min-w-0">
          <div className="text-xs font-black uppercase tracking-wider text-text-muted mb-1">
            {cohort.level || '—'} · {cohort.academic_year || 'no year'}
          </div>
          <h1 className="text-3xl font-black text-text truncate">{cohort.name}</h1>
        </div>
        {canManage && (
          <button
            onClick={() => navigate(`/admin/cohorts/${cohort.id}/edit`)}
            className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-bold border border-border bg-background text-text hover:bg-background-alt"
            title="Edit cohort"
          >
            <Edit3 size={12} /> Edit
          </button>
        )}
        <span className={`px-3 py-1 rounded-full text-xs font-black uppercase tracking-wider bg-primary/10 text-primary`}>
          {cohort.programme}
        </span>
      </div>

      {/* Tabs */}
      <div className="flex gap-1 border-b border-border overflow-x-auto">
        {(['overview', 'students', 'classes', 'exam-groups'] as const).map((t) => (
          <button
            key={t}
            onClick={() => setTab(t)}
            className={`px-4 py-2 text-sm font-bold uppercase tracking-wider border-b-2 whitespace-nowrap ${
              tab === t ? 'border-primary text-primary' : 'border-transparent text-text-muted hover:text-text'
            }`}
          >
            {t === 'overview' ? 'Overview' : t === 'exam-groups' ? 'Exam Groups' : t.charAt(0).toUpperCase() + t.slice(1)}
            {t === 'students' && ` (${cohort.students?.length ?? 0})`}
            {t === 'classes' && ` (${cohort.classes?.length ?? 0})`}
            {t === 'exam-groups' && ` (${cohort.exam_groups?.length ?? 0})`}
          </button>
        ))}
      </div>

      {tab === 'overview' && <OverviewTab cohort={cohort} />}
      {tab === 'students' && (
        <StudentsTab
          cohort={cohort}
          canManage={canManage}
          onAdd={() => setShowAddStudents(true)}
        />
      )}
      {tab === 'classes' && (
        <ClassesTab
          cohort={cohort}
          canManage={canManage}
          onLink={() => setShowLinkClass(true)}
        />
      )}
      {tab === 'exam-groups' && (
        <ExamGroupsTab
          cohort={cohort}
          canManage={canManage}
          onLink={() => setShowLinkExamGroup(true)}
        />
      )}

      {showAddStudents && (
        <AddStudentsModal
          cohortId={cohortId}
          existingStudentIds={(cohort.students || []).map((s) => s.id)}
          onClose={() => setShowAddStudents(false)}
        />
      )}
      {showLinkClass && (
        <LinkClassModal cohortId={cohortId} onClose={() => setShowLinkClass(false)} />
      )}
      {showLinkExamGroup && (
        <LinkExamGroupModal cohortId={cohortId} onClose={() => setShowLinkExamGroup(false)} />
      )}
    </div>
  );
}

function OverviewTab({ cohort }: { cohort: CohortDetailT }) {
  return (
    <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
      <StatCard icon={Users} label="Students" value={cohort.students?.length ?? 0} />
      <StatCard icon={BookOpen} label="Classes" value={cohort.classes?.length ?? 0} />
      <StatCard icon={GraduationCap} label="Exam Groups" value={cohort.exam_groups?.length ?? 0} />
      {cohort.description && (
        <div className="md:col-span-3 bg-card border border-border rounded-2xl p-5">
          <div className="text-xs font-black uppercase tracking-wider text-text-muted mb-2">Description</div>
          <p className="text-sm text-text-secondary whitespace-pre-wrap">{cohort.description}</p>
        </div>
      )}
    </div>
  );
}

function StatCard({ icon: Icon, label, value }: { icon: any; label: string; value: number }) {
  return (
    <div className="bg-card border border-border rounded-2xl p-5">
      <div className="flex items-center gap-3">
        <div className="w-10 h-10 rounded-xl bg-primary/10 text-primary flex items-center justify-center">
          <Icon size={20} />
        </div>
        <div>
          <div className="text-2xl font-black text-text">{value}</div>
          <div className="text-xs text-text-muted uppercase tracking-wider font-bold">{label}</div>
        </div>
      </div>
    </div>
  );
}

function StudentsTab({ cohort, canManage, onAdd }: { cohort: CohortDetailT; canManage: boolean; onAdd: () => void }) {
  const removeStudent = useCohortsStore((s) => s.removeStudent);
  const students = cohort.students || [];
  return (
    <div className="bg-card border border-border rounded-2xl p-5 space-y-3">
      <div className="flex items-center justify-between">
        <h2 className="text-lg font-black text-text">Students in this cohort</h2>
        {canManage && (
          <button onClick={onAdd} className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-bold bg-primary text-white">
            <Plus size={12} /> Add students
          </button>
        )}
      </div>
      {students.length === 0 ? (
        <div className="text-center text-text-muted py-6 text-sm">No students in this cohort yet.</div>
      ) : (
        <div className="space-y-1">
          {students.map((s) => (
            <div key={s.id} className="flex items-center justify-between p-2 rounded-lg hover:bg-background-alt">
              <div className="min-w-0 flex-1">
                <div className="font-bold text-sm text-text">{s.first_name} {s.last_name}</div>
                <div className="text-xs text-text-muted truncate">{s.email}</div>
              </div>
              {canManage && (
                <button
                  onClick={() => {
                    if (confirm(`Remove ${s.first_name} ${s.last_name} from this cohort?`)) {
                      removeStudent(cohort.id, s.id);
                    }
                  }}
                  className="p-2 text-rose-500 hover:bg-rose-500/10 rounded-lg"
                  title="Remove from cohort"
                >
                  <Trash2 size={14} />
                </button>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function ClassesTab({ cohort, canManage, onLink }: { cohort: CohortDetailT; canManage: boolean; onLink: () => void }) {
  const unlinkClass = useCohortsStore((s) => s.unlinkClass);
  const classes = cohort.classes || [];
  return (
    <div className="bg-card border border-border rounded-2xl p-5 space-y-3">
      <div className="flex items-center justify-between">
        <h2 className="text-lg font-black text-text">Classes in this cohort</h2>
        {canManage && (
          <button onClick={onLink} className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-bold bg-primary text-white">
            <Plus size={12} /> Link class
          </button>
        )}
      </div>
      {classes.length === 0 ? (
        <div className="text-center text-text-muted py-6 text-sm">No classes linked yet.</div>
      ) : (
        <div className="space-y-1">
          {classes.map((c) => (
            <div key={c.id} className="flex items-center justify-between p-2 rounded-lg hover:bg-background-alt">
              <div className="min-w-0 flex-1">
                <div className="font-bold text-sm text-text">
                  {c.name}{c.section ? ` ${c.section}` : ''}
                  {c.capacity ? <span className="ml-2 text-xs text-text-muted">capacity {c.capacity}</span> : null}
                </div>
                {c.class_teacher_name && (
                  <div className="text-xs text-text-muted">Form tutor: {c.class_teacher_name}</div>
                )}
              </div>
              {canManage && (
                <button
                  onClick={() => {
                    if (confirm(`Unlink ${c.name} from this cohort?`)) {
                      unlinkClass(cohort.id, c.id);
                    }
                  }}
                  className="p-2 text-rose-500 hover:bg-rose-500/10 rounded-lg"
                  title="Unlink class"
                >
                  <Trash2 size={14} />
                </button>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function ExamGroupsTab({ cohort, canManage, onLink }: { cohort: CohortDetailT; canManage: boolean; onLink: () => void }) {
  const unlinkExamGroup = useCohortsStore((s) => s.unlinkExamGroup);
  const egs = cohort.exam_groups || [];
  return (
    <div className="bg-card border border-border rounded-2xl p-5 space-y-3">
      <div className="flex items-center justify-between">
        <h2 className="text-lg font-black text-text">Exam paper sets</h2>
        {canManage && (
          <button onClick={onLink} className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-bold bg-primary text-white">
            <Plus size={12} /> Link exam group
          </button>
        )}
      </div>
      {egs.length === 0 ? (
        <div className="text-center text-text-muted py-6 text-sm">No exam paper sets linked yet.</div>
      ) : (
        <div className="space-y-1">
          {egs.map((eg) => (
            <div key={eg.id} className="flex items-center justify-between p-2 rounded-lg hover:bg-background-alt">
              <div className="min-w-0 flex-1">
                <div className="font-bold text-sm text-text">{eg.name}</div>
                <div className="text-xs text-text-muted">
                  {eg.exam_type && `${eg.exam_type}`}
                  {eg.academic_year && ` · ${eg.academic_year}`}
                  {eg.term && ` · ${eg.term}`}
                </div>
              </div>
              {canManage && (
                <button
                  onClick={() => {
                    if (confirm(`Unlink ${eg.name} from this cohort?`)) {
                      unlinkExamGroup(cohort.id, eg.id);
                    }
                  }}
                  className="p-2 text-rose-500 hover:bg-rose-500/10 rounded-lg"
                  title="Unlink exam group"
                >
                  <Trash2 size={14} />
                </button>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ---- Modals --------------------------------------------------------------

function ModalShell({ title, onClose, children }: { title: string; onClose: () => void; children: React.ReactNode }) {
  return (
    <div className="fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-4" onClick={onClose}>
      <div className="bg-card border border-border rounded-2xl shadow-2xl w-full max-w-2xl p-6 relative" onClick={(e) => e.stopPropagation()}>
        <button onClick={onClose} className="absolute top-4 right-4 text-text-muted hover:text-text"><X size={18} /></button>
        <h2 className="text-lg font-black text-text mb-4">{title}</h2>
        {children}
      </div>
    </div>
  );
}

function AddStudentsModal({ cohortId, existingStudentIds, onClose }: { cohortId: number; existingStudentIds: number[]; onClose: () => void }) {
  const addStudents = useCohortsStore((s) => s.addStudents);
  const [students, setStudents] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [search, setSearch] = useState('');
  const [selected, setSelected] = useState<Set<number>>(new Set());
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    setLoading(true);
    api.get('/users', { params: { role: 'student', limit: 500 } })
      .then((r) => {
        const list = (r.data.users || []).filter((u: any) => !existingStudentIds.includes(u.id));
        setStudents(list);
      })
      .catch(() => setStudents([]))
      .finally(() => setLoading(false));
  }, [existingStudentIds]);

  const filtered = students.filter((u) => {
    if (!search) return true;
    const q = search.toLowerCase();
    return u.first_name?.toLowerCase().includes(q) || u.last_name?.toLowerCase().includes(q) || u.email?.toLowerCase().includes(q);
  });

  const handleSubmit = async () => {
    if (selected.size === 0) return setError('Pick at least one student');
    setSubmitting(true);
    setError(null);
    try {
      await addStudents(cohortId, Array.from(selected));
      onClose();
    } catch (e: any) {
      setError(e.message || 'Failed');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <ModalShell title="Add students to cohort" onClose={onClose}>
      <div className="relative mb-3">
        <input
          type="text"
          placeholder="Search students…"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="w-full px-3 py-2 rounded-xl border border-border bg-background text-text text-sm"
        />
      </div>
      <div className="max-h-80 overflow-y-auto border border-border rounded-xl divide-y divide-border/50">
        {loading ? (
          <div className="p-4 text-center text-text-muted text-sm flex items-center justify-center gap-2"><Loader2 size={14} className="animate-spin" /> Loading…</div>
        ) : filtered.length === 0 ? (
          <div className="p-4 text-center text-text-muted text-sm">No matching students.</div>
        ) : (
          filtered.map((u) => {
            const checked = selected.has(u.id);
            return (
              <label key={u.id} className="flex items-center gap-3 p-2 hover:bg-background-alt cursor-pointer">
                <input
                  type="checkbox"
                  checked={checked}
                  onChange={(e) => {
                    const next = new Set(selected);
                    if (e.target.checked) next.add(u.id); else next.delete(u.id);
                    setSelected(next);
                  }}
                  className="w-4 h-4"
                />
                <div className="min-w-0 flex-1">
                  <div className="font-bold text-sm text-text truncate">{u.first_name} {u.last_name}</div>
                  <div className="text-xs text-text-muted truncate">{u.email}</div>
                </div>
              </label>
            );
          })
        )}
      </div>
      {error && <div className="text-sm text-rose-500 mt-2">{error}</div>}
      <div className="flex items-center justify-end gap-2 mt-4">
        <span className="text-xs text-text-muted mr-auto">{selected.size} selected</span>
        <button onClick={onClose} className="px-4 py-2 rounded-xl text-sm font-bold text-text-secondary hover:bg-background-alt">Cancel</button>
        <button
          onClick={handleSubmit}
          disabled={submitting || selected.size === 0}
          className="px-4 py-2 rounded-xl text-sm font-bold bg-primary text-white disabled:opacity-50"
        >
          {submitting ? 'Adding…' : `Add ${selected.size || ''}`}
        </button>
      </div>
    </ModalShell>
  );
}

function LinkClassModal({ cohortId, onClose }: { cohortId: number; onClose: () => void }) {
  const linkClass = useCohortsStore((s) => s.linkClass);
  const [classes, setClasses] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    setLoading(true);
    api.get('/classes', { params: { limit: 500 } })
      .then((r) => setClasses(Array.isArray(r.data) ? r.data : []))
      .catch(() => setClasses([]))
      .finally(() => setLoading(false));
  }, []);

  const handleSubmit = async (classId: number) => {
    setSubmitting(true);
    setError(null);
    try {
      await linkClass(cohortId, classId);
      onClose();
    } catch (e: any) {
      setError(e.message || 'Failed');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <ModalShell title="Link a class" onClose={onClose}>
      <div className="max-h-80 overflow-y-auto border border-border rounded-xl divide-y divide-border/50">
        {loading ? (
          <div className="p-4 text-center text-text-muted text-sm flex items-center justify-center gap-2"><Loader2 size={14} className="animate-spin" /> Loading…</div>
        ) : classes.length === 0 ? (
          <div className="p-4 text-center text-text-muted text-sm">No classes available.</div>
        ) : (
          classes.map((c) => (
            <button
              key={c.id}
              onClick={() => handleSubmit(c.id)}
              disabled={submitting}
              className="w-full text-left p-3 hover:bg-background-alt disabled:opacity-50"
            >
              <div className="font-bold text-sm text-text">{c.name}{c.section ? ` ${c.section}` : ''}</div>
              {c.description && <div className="text-xs text-text-muted">{c.description}</div>}
            </button>
          ))
        )}
      </div>
      {error && <div className="text-sm text-rose-500 mt-2">{error}</div>}
    </ModalShell>
  );
}

function LinkExamGroupModal({ cohortId, onClose }: { cohortId: number; onClose: () => void }) {
  const linkExamGroup = useCohortsStore((s) => s.linkExamGroup);
  const [examGroups, setExamGroups] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    setLoading(true);
    api.get('/exams/groups', { params: { limit: 500 } })
      .then((r) => setExamGroups(r.data.groups || r.data || []))
      .catch(() => setExamGroups([]))
      .finally(() => setLoading(false));
  }, []);

  const handleSubmit = async (egId: number) => {
    setSubmitting(true);
    setError(null);
    try {
      await linkExamGroup(cohortId, egId);
      onClose();
    } catch (e: any) {
      setError(e.message || 'Failed');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <ModalShell title="Link an exam paper set" onClose={onClose}>
      <div className="max-h-80 overflow-y-auto border border-border rounded-xl divide-y divide-border/50">
        {loading ? (
          <div className="p-4 text-center text-text-muted text-sm flex items-center justify-center gap-2"><Loader2 size={14} className="animate-spin" /> Loading…</div>
        ) : examGroups.length === 0 ? (
          <div className="p-4 text-center text-text-muted text-sm">No exam groups available.</div>
        ) : (
          examGroups.map((eg) => (
            <button
              key={eg.id}
              onClick={() => handleSubmit(eg.id)}
              disabled={submitting}
              className="w-full text-left p-3 hover:bg-background-alt disabled:opacity-50"
            >
              <div className="font-bold text-sm text-text">{eg.name}</div>
              {eg.exam_type && <div className="text-xs text-text-muted">{eg.exam_type}{eg.academic_year ? ` · ${eg.academic_year}` : ''}</div>}
            </button>
          ))
        )}
      </div>
      {error && <div className="text-sm text-rose-500 mt-2">{error}</div>}
    </ModalShell>
  );
}
