/**
 * CoverAssignmentForm — modal for granting a class cover / auxiliary role.
 *
 * Phase 1 PR 1 (2026-07-22).
 *
 * Two modes:
 *   - "cover" (default): pre-fills scope_class_id and explains the
 *     time-scoped cover semantics. Used from the class detail page to
 *     hand a class over to another teacher for a date range.
 *   - "auxiliary": no scope, just role + reason + optional expiry. Used
 *     from the user detail page to grant "this teacher is also a librarian".
 *
 * Reads teachers + classes from the existing /api/users and /api/classes
 * endpoints. Submits via the userRoles store. On success, calls the
 * parent's onGranted callback so the caller can refresh the active-covers
 * list or the user detail.
 */

import React, { useEffect, useState } from 'react';
import { X, UserPlus, Calendar } from 'lucide-react';
import api from '../store/api';
import { useUserRolesStore, SUPPORTED_AUX_ROLES } from '../store/userRoles';
import { useAuthStore } from '../store/auth';

interface CoverAssignmentFormProps {
  mode?: 'cover' | 'auxiliary';
  // For "cover" mode: lock the class. For "auxiliary" mode: lock the user.
  fixedClassId?: number;
  fixedUserId?: number;
  defaultRole?: string;
  onClose: () => void;
  onGranted?: () => void;
}

const today = () => new Date().toISOString().slice(0, 10);
const twoWeeks = () => {
  const d = new Date();
  d.setDate(d.getDate() + 14);
  return d.toISOString().slice(0, 10);
};

export const CoverAssignmentForm: React.FC<CoverAssignmentFormProps> = ({
  mode = 'cover',
  fixedClassId,
  fixedUserId,
  defaultRole = 'teacher',
  onClose,
  onGranted,
}) => {
  const { user: currentUser } = useAuthStore();
  const grantRole = useUserRolesStore((s) => s.grantRole);

  const [userId, setUserId] = useState<number | ''>(fixedUserId ?? '');
  const [role, setRole] = useState<string>(defaultRole);
  const [classId, setClassId] = useState<number | ''>(fixedClassId ?? '');
  const [startsAt, setStartsAt] = useState<string>(today());
  const [expiresAt, setExpiresAt] = useState<string>(twoWeeks());
  const [reason, setReason] = useState<string>('');
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const [teachers, setTeachers] = useState<any[]>([]);
  const [classes, setClasses] = useState<any[]>([]);

  useEffect(() => {
    if (mode === 'auxiliary' && !fixedUserId) {
      api.get('/users', { params: { role: 'teacher', limit: 200 } })
        .then((r) => setTeachers(r.data.users || r.data || []))
        .catch(() => setTeachers([]));
    }
    if (mode === 'cover' && !fixedClassId) {
      api.get('/classes', { params: { limit: 200 } })
        .then((r) => setClasses(Array.isArray(r.data) ? r.data : []))
        .catch(() => setClasses([]));
    }
  }, [mode, fixedUserId, fixedClassId]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    if (!userId) return setError('Pick a user to grant the role to');
    if (mode === 'cover' && !classId) return setError('Pick a class for the cover');
    if (!reason.trim()) return setError('A reason is required (e.g. "covering sick leave for Mrs Moyo")');
    setSubmitting(true);
    try {
      await grantRole(Number(userId), {
        role,
        scope_class_id: mode === 'cover' ? Number(classId) : null,
        starts_at: startsAt || null,
        expires_at: expiresAt || null,
        reason: reason.trim(),
      });
      onGranted?.();
      onClose();
    } catch (err: any) {
      setError(err.message || 'Failed to grant role');
    } finally {
      setSubmitting(false);
    }
  };

  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-lg p-6 relative"
        onClick={(e) => e.stopPropagation()}
      >
        <button
          type="button"
          onClick={onClose}
          className="absolute top-4 right-4 text-text-muted hover:text-text"
          aria-label="Close"
        >
          <X size={18} />
        </button>
        <div className="flex items-center gap-2 mb-4">
          <UserPlus size={20} className="text-primary" />
          <h2 className="text-lg font-black text-text">
            {mode === 'cover' ? 'Assign Class Cover' : 'Grant Auxiliary Role'}
          </h2>
        </div>
        <p className="text-xs text-text-muted mb-4">
          {mode === 'cover'
            ? 'A cover lets a non-form-tutor take a class for a date range. After expiry the RBAC layer auto-removes the grant — no cleanup needed.'
            : 'An auxiliary role adds a permission beyond the user\'s primary role (e.g. "this teacher is also a librarian").'}
        </p>

        <form onSubmit={handleSubmit} className="space-y-4">
          {!fixedUserId && (
            <div>
              <label className="block text-xs font-bold uppercase tracking-wider text-text-muted mb-1">User</label>
              <select
                className="w-full px-3 py-2 rounded-xl border border-border bg-background text-text"
                value={userId}
                onChange={(e) => setUserId(e.target.value ? Number(e.target.value) : '')}
                required
              >
                <option value="">— pick a user —</option>
                {(mode === 'auxiliary' ? teachers : teachers.length ? teachers : []).map((u) => (
                  <option key={u.id} value={u.id}>
                    {u.first_name} {u.last_name} ({u.email})
                  </option>
                ))}
              </select>
            </div>
          )}

          <div>
            <label className="block text-xs font-bold uppercase tracking-wider text-text-muted mb-1">Role</label>
            <select
              className="w-full px-3 py-2 rounded-xl border border-border bg-background text-text"
              value={role}
              onChange={(e) => setRole(e.target.value)}
              required
            >
              {SUPPORTED_AUX_ROLES.map((r) => (
                <option key={r} value={r}>{r}</option>
              ))}
            </select>
          </div>

          {mode === 'cover' && !fixedClassId && (
            <div>
              <label className="block text-xs font-bold uppercase tracking-wider text-text-muted mb-1">Class</label>
              <select
                className="w-full px-3 py-2 rounded-xl border border-border bg-background text-text"
                value={classId}
                onChange={(e) => setClassId(e.target.value ? Number(e.target.value) : '')}
                required
              >
                <option value="">— pick a class —</option>
                {classes.map((c) => (
                  <option key={c.id} value={c.id}>{c.name}{c.section ? ` ${c.section}` : ''}</option>
                ))}
              </select>
            </div>
          )}

          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs font-bold uppercase tracking-wider text-text-muted mb-1">
                <Calendar size={11} className="inline mr-1" />Starts
              </label>
              <input
                type="date"
                className="w-full px-3 py-2 rounded-xl border border-border bg-background text-text"
                value={startsAt}
                onChange={(e) => setStartsAt(e.target.value)}
              />
            </div>
            <div>
              <label className="block text-xs font-bold uppercase tracking-wider text-text-muted mb-1">
                <Calendar size={11} className="inline mr-1" />Expires
              </label>
              <input
                type="date"
                className="w-full px-3 py-2 rounded-xl border border-border bg-background text-text"
                value={expiresAt}
                onChange={(e) => setExpiresAt(e.target.value)}
              />
            </div>
          </div>

          <div>
            <label className="block text-xs font-bold uppercase tracking-wider text-text-muted mb-1">Reason</label>
            <input
              type="text"
              placeholder="e.g. Covering Mrs Moyo (sick leave) — ticket #123"
              className="w-full px-3 py-2 rounded-xl border border-border bg-background text-text"
              value={reason}
              onChange={(e) => setReason(e.target.value)}
              required
            />
          </div>

          {error && <div className="text-sm text-rose-500 bg-rose-500/10 border border-rose-500/30 rounded-xl px-3 py-2">{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="px-4 py-2 rounded-xl text-sm font-bold bg-primary text-white shadow-lg shadow-primary/20 hover:opacity-95 disabled:opacity-50"
            >
              {submitting ? 'Granting…' : 'Grant Role'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default CoverAssignmentForm;
