/**
 * CreateClassWizard — modal for creating a class with optional form
 * tutor + initial roster in one flow.
 *
 * Phase 1 PR 3 (2026-07-22). Calls
 * `POST /api/classes?withAssignments=1` with the composed payload.
 * On success, fires `onCreated(class)` so the parent (Classes page)
 * can prepend the new class to the list and navigate to its detail.
 */

import React, { useEffect, useState } from 'react';
import { X, Save, Check, Users, UserCheck } from 'lucide-react';
import api from '../store/api';

interface TeacherOpt {
  id: number;
  first_name: string;
  last_name: string;
  email: string;
}

interface StudentOpt {
  id: number;
  first_name: string;
  last_name: string;
  email: string;
}

interface CreateClassWizardProps {
  onClose: () => void;
  onCreated?: (cls: { id: number; name: string; section: string | null }) => void;
}

const blank = {
  name: '',
  section: '',
  capacity: 40,
  description: '',
  classTeacherId: null as number | null,
  initialStudentIds: [] as number[],
};

export const CreateClassWizard: React.FC<CreateClassWizardProps> = ({ onClose, onCreated }) => {
  const [form, setForm] = useState(blank);
  const [teachers, setTeachers] = useState<TeacherOpt[]>([]);
  const [students, setStudents] = useState<StudentOpt[]>([]);
  const [loadingRoster, setLoadingRoster] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [studentSearch, setStudentSearch] = useState('');

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const [tRes, sRes] = await Promise.all([
          api.get('/users', { params: { role: 'teacher', limit: 200 } }),
          api.get('/users', { params: { role: 'student', limit: 500 } }),
        ]);
        if (cancelled) return;
        setTeachers(tRes.data.users || tRes.data || []);
        setStudents(sRes.data.users || sRes.data || []);
      } catch {
        // non-fatal — the wizard still works without preloaded lists
      } finally {
        if (!cancelled) setLoadingRoster(false);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, []);

  const setField = <K extends keyof typeof form>(k: K, v: typeof form[K]) => {
    setForm((f) => ({ ...f, [k]: v }));
  };

  const toggleStudent = (id: number) => {
    setForm((f) => ({
      ...f,
      initialStudentIds: f.initialStudentIds.includes(id)
        ? f.initialStudentIds.filter((s) => s !== id)
        : [...f.initialStudentIds, id],
    }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    if (!form.name.trim()) return setError('Class name is required');

    setSubmitting(true);
    try {
      const { data } = await api.post('/classes?withAssignments=1', {
        name: form.name.trim(),
        section: form.section.trim() || null,
        capacity: Number(form.capacity) || 40,
        description: form.description.trim() || null,
        classTeacherId: form.classTeacherId,
        initialStudentIds: form.initialStudentIds,
      });
      const created = data.class || data;
      onCreated?.({ id: created.id, name: created.name, section: created.section });
      onClose();
    } catch (err: any) {
      setError(err.response?.data?.error || err.message || 'Failed to create class');
    } finally {
      setSubmitting(false);
    }
  };

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

  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-3xl p-6 relative max-h-[90vh] overflow-y-auto"
        onClick={(e) => e.stopPropagation()}
      >
        <button
          onClick={onClose}
          className="absolute top-4 right-4 text-text-muted hover:text-text"
          title="Close"
        >
          <X size={18} />
        </button>
        <h2 className="text-lg font-black text-text mb-1">Create class</h2>
        <p className="text-xs text-text-muted mb-4">
          One flow: pick the class details, assign a form tutor (optional), and bulk-enrol an initial roster (optional). You can change all of these later from the class detail page.
        </p>

        <form onSubmit={handleSubmit} className="space-y-5">
          <section className="space-y-3">
            <h3 className="text-xs font-black uppercase tracking-wider text-text-muted">Class details</h3>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
              <label className="block md:col-span-2">
                <span className="text-xs font-bold uppercase tracking-wider text-text-muted">Name *</span>
                <input
                  type="text"
                  value={form.name}
                  onChange={(e) => setField('name', e.target.value)}
                  placeholder="Form 1A"
                  className="mt-1 w-full px-3 py-2 rounded-xl border border-border bg-background text-text text-sm"
                  required
                />
              </label>
              <label className="block">
                <span className="text-xs font-bold uppercase tracking-wider text-text-muted">Section</span>
                <input
                  type="text"
                  value={form.section}
                  onChange={(e) => setField('section', e.target.value)}
                  placeholder="A"
                  className="mt-1 w-full px-3 py-2 rounded-xl border border-border bg-background text-text text-sm"
                />
              </label>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
              <label className="block">
                <span className="text-xs font-bold uppercase tracking-wider text-text-muted">Capacity</span>
                <input
                  type="number"
                  min={1}
                  value={form.capacity}
                  onChange={(e) => setField('capacity', Number(e.target.value))}
                  className="mt-1 w-full px-3 py-2 rounded-xl border border-border bg-background text-text text-sm"
                />
              </label>
              <label className="block md:col-span-2">
                <span className="text-xs font-bold uppercase tracking-wider text-text-muted">Description</span>
                <input
                  type="text"
                  value={form.description}
                  onChange={(e) => setField('description', e.target.value)}
                  placeholder="Optional notes for the academic office"
                  className="mt-1 w-full px-3 py-2 rounded-xl border border-border bg-background text-text text-sm"
                />
              </label>
            </div>
          </section>

          <section className="space-y-2">
            <h3 className="text-xs font-black uppercase tracking-wider text-text-muted flex items-center gap-1.5">
              <UserCheck size={12} /> Form tutor (optional)
            </h3>
            <select
              value={form.classTeacherId ?? ''}
              onChange={(e) => setField('classTeacherId', e.target.value ? Number(e.target.value) : null)}
              className="w-full px-3 py-2 rounded-xl border border-border bg-background text-text text-sm"
            >
              <option value="">— No form tutor —</option>
              {teachers.map((t) => (
                <option key={t.id} value={t.id}>
                  {t.first_name} {t.last_name} ({t.email})
                </option>
              ))}
            </select>
          </section>

          <section className="space-y-2">
            <h3 className="text-xs font-black uppercase tracking-wider text-text-muted flex items-center gap-1.5">
              <Users size={12} /> Initial roster (optional, {form.initialStudentIds.length} selected)
            </h3>
            <input
              type="text"
              value={studentSearch}
              onChange={(e) => setStudentSearch(e.target.value)}
              placeholder="Search students…"
              className="w-full px-3 py-2 rounded-xl border border-border bg-background text-text text-sm"
            />
            <div className="max-h-48 overflow-y-auto border border-border rounded-xl divide-y divide-border/50">
              {loadingRoster ? (
                <div className="p-3 text-center text-text-muted text-sm">Loading…</div>
              ) : filteredStudents.length === 0 ? (
                <div className="p-3 text-center text-text-muted text-sm">No matching students.</div>
              ) : (
                filteredStudents.map((s) => {
                  const checked = form.initialStudentIds.includes(s.id);
                  return (
                    <label
                      key={s.id}
                      className="flex items-center gap-3 p-2 hover:bg-background-alt cursor-pointer"
                    >
                      <input
                        type="checkbox"
                        checked={checked}
                        onChange={() => toggleStudent(s.id)}
                        className="w-4 h-4"
                      />
                      <div className="min-w-0 flex-1">
                        <div className="font-bold text-sm text-text truncate">
                          {s.first_name} {s.last_name}
                        </div>
                        <div className="text-xs text-text-muted truncate">{s.email}</div>
                      </div>
                      {checked && <Check size={14} className="text-primary" />}
                    </label>
                  );
                })
              )}
            </div>
          </section>

          {error && <div className="text-sm text-rose-500">{error}</div>}

          <div className="flex items-center justify-end gap-2 pt-2">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 rounded-xl text-sm font-bold text-text-secondary hover:bg-background-alt"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={submitting}
              className="inline-flex items-center gap-1.5 px-4 py-2 rounded-xl text-sm font-bold bg-primary text-white disabled:opacity-50"
            >
              <Save size={14} /> {submitting ? 'Creating…' : 'Create class'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default CreateClassWizard;
