/**
 * CohortForm — modal for creating or editing a student cohort.
 *
 * Phase 1 PR 2 (2026-07-22). Mirrors the modal pattern from
 * CoverAssignmentForm.tsx: fixed inset-0 overlay, inner stopPropagation,
 * Cancel + Save action buttons, optimistic close on success.
 *
 * The `programme` dropdown drives `level` suggestions via
 * PROGRAMME_LEVELS — admins can still type a custom level (the datalist
 * is suggestion-only, not enforcing). This is intentional: different
 * schools name grades differently and we don't want to block creation
 * over a label mismatch.
 */

import React, { useEffect, useState } from 'react';
import { X, Save } from 'lucide-react';
import { useCohortsStore, Cohort, SUPPORTED_PROGRAMMES } from '../store/cohorts';

// Programme → typical level options. "other" is intentionally empty: it
// forces a free-text level so admins don't pick something misleading.
const PROGRAMME_LEVELS: Record<string, string[]> = {
  zimsec:  ['ECD A', 'ECD B', 'Grade 1', 'Grade 2', 'Grade 3', 'Grade 4',
            'Grade 5', 'Grade 6', 'Grade 7', 'Form 1', 'Form 2', 'Form 3',
            'Form 4', 'Form 5', 'Form 6'],
  igcse:   ['Year 1', 'Year 2', 'IGCSE'],
  as:      ['Form 5', 'AS Level'],
  a2:      ['Form 6', 'A2 Level'],
  primary: ['Reception', 'Year 1', 'Year 2', 'Year 3', 'Year 4', 'Year 5', 'Year 6'],
  other:   [],
};

interface CohortFormProps {
  cohort?: Cohort | null;        // null/undefined = create
  onClose: () => void;
  onSaved?: (cohort: Cohort) => void;
}

const blankForm = {
  name: '',
  programme: 'zimsec' as Cohort['programme'],
  level: '',
  academic_year: String(new Date().getFullYear()),
  description: '',
  start_date: '',
  end_date: '',
  is_active: true,
};

export const CohortForm: React.FC<CohortFormProps> = ({ cohort, onClose, onSaved }) => {
  const isEdit = !!cohort;
  const createCohort = useCohortsStore((s) => s.createCohort);
  const updateCohort = useCohortsStore((s) => s.updateCohort);

  const [form, setForm] = useState(blankForm);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (cohort) {
      setForm({
        name: cohort.name || '',
        programme: cohort.programme || 'zimsec',
        level: cohort.level || '',
        academic_year: cohort.academic_year || String(new Date().getFullYear()),
        description: cohort.description || '',
        start_date: cohort.start_date || '',
        end_date: cohort.end_date || '',
        is_active: cohort.is_active ?? true,
      });
    }
  }, [cohort]);

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

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

    setSubmitting(true);
    try {
      const payload: Partial<Cohort> = {
        name: form.name.trim(),
        programme: form.programme,
        level: form.level.trim() || null,
        academic_year: form.academic_year.trim() || null,
        description: form.description.trim() || null,
        start_date: form.start_date || null,
        end_date: form.end_date || null,
        is_active: form.is_active,
      };
      const saved = isEdit
        ? await updateCohort(cohort!.id, payload)
        : await createCohort(payload);
      onSaved?.(saved);
      onClose();
    } catch (err: any) {
      setError(err.message || 'Failed to save cohort');
    } finally {
      setSubmitting(false);
    }
  };

  const levelSuggestions = PROGRAMME_LEVELS[form.programme] || [];

  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 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">
          {isEdit ? 'Edit cohort' : 'New cohort'}
        </h2>
        <p className="text-xs text-text-muted mb-4">
          {isEdit
            ? 'Update cohort details. Programme + year help exams pick the right paper set.'
            : 'A cohort groups students by programme (ZIMSEC / IGCSE / AS / A2) for the academic year.'}
        </p>

        <form onSubmit={handleSubmit} className="space-y-4">
          <Field label="Name" required>
            <input
              type="text"
              value={form.name}
              onChange={(e) => setField('name', e.target.value)}
              placeholder="Form 4 IGCSE 2026"
              className="w-full px-3 py-2 rounded-xl border border-border bg-background text-text text-sm"
              required
            />
          </Field>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <Field label="Programme" required>
              <select
                value={form.programme}
                onChange={(e) => setField('programme', e.target.value as Cohort['programme'])}
                className="w-full px-3 py-2 rounded-xl border border-border bg-background text-text text-sm"
              >
                {SUPPORTED_PROGRAMMES.map((p) => (
                  <option key={p.value} value={p.value}>{p.label}</option>
                ))}
              </select>
            </Field>

            <Field
              label="Level"
              hint={levelSuggestions.length ? 'Suggested; pick or type your own' : 'Type your own level'}
            >
              <input
                type="text"
                list="cohort-level-suggestions"
                value={form.level}
                onChange={(e) => setField('level', e.target.value)}
                placeholder="Form 4"
                className="w-full px-3 py-2 rounded-xl border border-border bg-background text-text text-sm"
              />
              <datalist id="cohort-level-suggestions">
                {levelSuggestions.map((l) => (
                  <option key={l} value={l} />
                ))}
              </datalist>
            </Field>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <Field label="Academic year">
              <input
                type="text"
                value={form.academic_year}
                onChange={(e) => setField('academic_year', e.target.value)}
                placeholder="2026"
                className="w-full px-3 py-2 rounded-xl border border-border bg-background text-text text-sm"
              />
            </Field>
            <Field label="Start date">
              <input
                type="date"
                value={form.start_date}
                onChange={(e) => setField('start_date', e.target.value)}
                className="w-full px-3 py-2 rounded-xl border border-border bg-background text-text text-sm"
              />
            </Field>
            <Field label="End date">
              <input
                type="date"
                value={form.end_date}
                onChange={(e) => setField('end_date', e.target.value)}
                className="w-full px-3 py-2 rounded-xl border border-border bg-background text-text text-sm"
              />
            </Field>
          </div>

          <Field label="Description">
            <textarea
              value={form.description}
              onChange={(e) => setField('description', e.target.value)}
              rows={3}
              placeholder="Optional. Notes for the academic office."
              className="w-full px-3 py-2 rounded-xl border border-border bg-background text-text text-sm"
            />
          </Field>

          <label className="flex items-center gap-2 text-sm text-text">
            <input
              type="checkbox"
              checked={form.is_active}
              onChange={(e) => setField('is_active', e.target.checked)}
              className="w-4 h-4"
            />
            <span>Active (un-check to archive)</span>
          </label>

          {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 ? 'Saving…' : isEdit ? 'Save cohort' : 'Create cohort'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

function Field({
  label,
  hint,
  required,
  children,
}: {
  label: string;
  hint?: string;
  required?: boolean;
  children: React.ReactNode;
}) {
  return (
    <label className="block">
      <span className="text-xs font-bold uppercase tracking-wider text-text-muted">
        {label}
        {required && <span className="text-rose-500 ml-1">*</span>}
      </span>
      <div className="mt-1">{children}</div>
      {hint && <span className="text-[0.7rem] text-text-muted mt-1 block">{hint}</span>}
    </label>
  );
}

export default CohortForm;
