/**
 * Class Room (formerly Course Scheme/Plan) — P1-UX-7 / PDF §9.
 *
 * Three sub-tabs:
 *   - Learning Material (PDF §8 — was "Material Assets" / "Curriculum
 *     Ledger"). Lesson plans surfaced with a "Virtual Class Room" button
 *     on any row whose lesson_plans.meet_url or .classroom_url is set
 *     (PDF §3 + §9 "VC/VM").
 *   - Export Scheme (PDF §9 — was "Export Intel"). Per-subject CSV
 *     download of lesson plans.
 *   - Learner (PDF §9 — was inside academic-progress). Per-learner
 *     progress placeholder. Full summary lives in the parent-side
 *     AcademicProgress page; this tab is the teacher-facing daily view.
 *
 * The route /class-room is gated in App.tsx to admin/principal/teacher.
 */

import { useEffect, useState } from 'react';
import {
  Calendar,
  ClipboardList,
  Download,
  GraduationCap,
  Layers,
  Link as LinkIcon,
  Search,
  Users,
  Video,
} from 'lucide-react';
import api from '../../store/api';

const TABS = [
  { id: 'learning-material', label: 'Learning Material', icon: Layers },
  { id: 'export-scheme', label: 'Export Scheme', icon: Download },
  { id: 'learner', label: 'Learner', icon: GraduationCap },
];

export function ClassRoom() {
  const [activeTab, setActiveTab] = useState('learning-material');
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [search, setSearch] = useState('');

  useEffect(() => {
    let alive = true;
    setLoading(true);
    api
      .get('/class-room')
      .then((r) => {
        if (!alive) return;
        setData(r.data);
        setError(null);
      })
      .catch((e) => {
        if (!alive) return;
        setError(e?.response?.data?.error || e?.message || 'Failed to load');
      })
      .finally(() => {
        if (alive) setLoading(false);
      });
    return () => {
      alive = false;
    };
  }, []);

  const filtered = (data?.lesson_plans ?? []).filter((lp) => {
    if (!search) return true;
    const t = (lp.topic || '').toLowerCase();
    const sub = (lp.subject_name || '').toLowerCase();
    return t.includes(search.toLowerCase()) || sub.includes(search.toLowerCase());
  });

  function handleExportCsv() {
    if (!filtered.length) return;
    const headers = [
      'date', 'subject', 'topic', 'teacher', 'status', 'meet_url', 'classroom_url',
    ];
    const rows = filtered.map((lp) => [
      lp.date || '',
      lp.subject_name || '',
      `"${(lp.topic || '').replace(/"/g, '""')}"`,
      lp.teacher_name || '',
      lp.status || '',
      lp.meet_url || '',
      lp.classroom_url || '',
    ].join(','));
    const csv = [headers.join(','), ...rows].join('\n');
    const blob = new Blob([csv], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `class-room-${new Date().toISOString().slice(0, 10)}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  }

  return (
    <div className="space-y-6 sm:space-y-8 animate-in fade-in duration-700 pb-24 sm:pb-10 px-4">
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
        <div>
          <h2 className="text-2xl sm:text-3xl font-black text-text tracking-tight">Class Room</h2>
          <nav className="flex text-[0.6rem] sm:text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted gap-2 items-center mt-1">
            <span>Faculty Workspace</span>
            <span>›</span>
            <span className="text-primary">Course Scheme / Plan</span>
          </nav>
        </div>

        <div className="grid grid-cols-3 gap-3 text-center">
          <Stat icon={ClipboardList} label="Total" value={data?.total ?? 0} />
          <Stat icon={LinkIcon} label="With Live Link" value={data?.with_live_link ?? 0} />
          <Stat icon={Calendar} label="Upcoming" value={data?.upcoming ?? 0} />
        </div>
      </div>

      <div className="flex flex-wrap items-center gap-2 border-b border-border">
        {TABS.map(({ id, label, icon: Icon }) => (
          <button
            key={id}
            onClick={() => setActiveTab(id)}
            className={`px-4 py-2 text-xs font-black uppercase tracking-widest rounded-t-xl flex items-center gap-2 transition-all ${
              activeTab === id
                ? 'bg-primary text-white'
                : 'text-text-muted hover:text-text'
            }`}
          >
            <Icon size={14} />
            {label}
          </button>
        ))}
        <div className="ml-auto flex items-center gap-2 pb-2">
          <Search size={14} className="text-text-muted" />
          <input
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Search topic or subject…"
            className="px-3 py-1.5 bg-muted border border-border rounded-lg text-xs focus:ring-1 focus:ring-primary/20 outline-none transition-all text-text"
          />
        </div>
      </div>

      {loading && <div className="text-xs text-text-muted">Loading…</div>}
      {error && (
        <div className="text-xs text-rose-500">{error}</div>
      )}
      {data?.note && (
        <div className="text-xs text-text-muted">{data.note}</div>
      )}

      {activeTab === 'learning-material' && (
        <div className="grid grid-cols-1 gap-3">
          {filtered.length === 0 ? (
            <Empty label="No lesson plans yet. Add one from the Teacher Tools page." />
          ) : (
            filtered.map((lp) => <LessonRow key={lp.uid || lp.id} lp={lp} />)
          )}
        </div>
      )}

      {activeTab === 'export-scheme' && (
        <div className="space-y-4">
          <p className="text-sm text-text-muted">
            Export every lesson plan in this Class Room as a CSV.
          </p>
          <button
            onClick={handleExportCsv}
            className="px-4 py-2 bg-primary text-white font-black uppercase tracking-widest rounded-xl text-xs"
          >
            <Download size={14} className="inline mr-2" />
            Export Scheme
          </button>
          <p className="text-xs text-text-muted">{filtered.length} record(s) will be exported.</p>
        </div>
      )}

      {activeTab === 'learner' && (
        <div className="space-y-4">
          <p className="text-sm text-text-muted">
            Per-learner progress view. The full subject-scoped rollup lives on the parent-side AcademicProgress page;
            this tab is the teacher's daily lookout.
          </p>
          <div className="text-xs text-text-muted flex items-center gap-2">
            <Users size={14} />
            Select an enrolled cohort to drill in (full integration is a follow-up).
          </div>
        </div>
      )}
    </div>
  );
}

function Stat({ icon: Icon, label, value }) {
  return (
    <div className="bg-card border border-border rounded-xl px-3 py-2">
      <Icon className="mx-auto text-primary" size={16} />
      <div className="text-lg font-black text-text">{value}</div>
      <div className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted">{label}</div>
    </div>
  );
}

function LessonRow({ lp }) {
  return (
    <div className="bg-card border border-border rounded-2xl p-4 flex flex-col sm:flex-row sm:items-center gap-3">
      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-2 text-[0.6rem] font-black uppercase tracking-widest text-text-muted">
          <span>{lp.date || 'no date'}</span>
          <span>·</span>
          <span>{lp.subject_name || '—'}</span>
          <span>·</span>
          <span>{lp.teacher_name || '—'}</span>
        </div>
        <div className="font-black text-text truncate">{lp.topic || 'Untitled lesson'}</div>
      </div>

      <div className="flex items-center gap-2">
        {lp.meet_url && (
          <a
            href={lp.meet_url}
            target="_blank"
            rel="noreferrer"
            className="inline-flex items-center gap-1 px-3 py-2 bg-emerald-500/15 text-emerald-700 dark:text-emerald-300 border border-emerald-500/30 rounded-xl text-xs font-black uppercase tracking-widest hover:bg-emerald-500/25 transition-all"
            title="Open Google Meet session"
          >
            <Video size={14} />
            VC
          </a>
        )}
        {lp.classroom_url && (
          <a
            href={lp.classroom_url}
            target="_blank"
            rel="noreferrer"
            className="inline-flex items-center gap-1 px-3 py-2 bg-blue-500/15 text-blue-700 dark:text-blue-300 border border-blue-500/30 rounded-xl text-xs font-black uppercase tracking-widest hover:bg-blue-500/25 transition-all"
            title="Open Google Classroom link"
          >
            <LinkIcon size={14} />
            VM
          </a>
        )}
        {!lp.meet_url && !lp.classroom_url && (
          <span className="text-xs text-text-muted">No live link</span>
        )}
      </div>
    </div>
  );
}

function Empty({ label }) {
  return (
    <div className="text-center py-10 text-text-muted text-sm">{label}</div>
  );
}

export default ClassRoom;
