/**
 * UserRoles — manage auxiliary role grants for any user.
 *
 * Phase 1 PR 1 (2026-07-22).
 *
 * Used by admins to:
 *   - grant a new auxiliary role (e.g. "Mrs Moyo is also a librarian")
 *   - grant a class cover (e.g. "Sports coach covers Form 3A for 2 weeks")
 *   - extend or revoke an existing grant
 *
 * Lists all users on the left, the selected user's grants on the right.
 * Reuses CoverAssignmentForm for the grant modal. The data flow:
 *   - load users via /api/users?role= (existing endpoint)
 *   - load grants for the selected user via the userRoles store
 *   - write through the store; refresh after every mutation
 */

import React, { useEffect, useState } from 'react';
import { UserPlus, Trash2, Clock, Search, Shield } from 'lucide-react';
import api from '../../store/api';
import { useUserRolesStore, UserRole } from '../../store/userRoles';
import CoverAssignmentForm from '../../components/CoverAssignmentForm';
import RoleBadge from '../../components/RoleBadge';

const fmt = (s: string | null) => (s ? new Date(s).toLocaleString() : '—');
const isExpired = (s: string | null) => s ? new Date(s) < new Date() : false;

export default function UserRolesPage() {
  const [users, setUsers] = useState<any[]>([]);
  const [search, setSearch] = useState('');
  const [selectedId, setSelectedId] = useState<number | null>(null);
  const [grants, setGrants] = useState<UserRole[]>([]);
  const [loading, setLoading] = useState(false);
  const [showForm, setShowForm] = useState(false);
  const [formMode, setFormMode] = useState<'cover' | 'auxiliary'>('cover');
  const fetchUserRoles = useUserRolesStore((s) => s.fetchUserRoles);
  const revokeGrant = useUserRolesStore((s) => s.revokeGrant);

  useEffect(() => {
    api.get('/users', { params: { limit: 500 } })
      .then((r) => setUsers(r.data.users || r.data || []))
      .catch(() => setUsers([]));
  }, []);

  useEffect(() => {
    if (!selectedId) {
      setGrants([]);
      return;
    }
    setLoading(true);
    fetchUserRoles(selectedId)
      .then((g) => setGrants(g))
      .catch(() => setGrants([]))
      .finally(() => setLoading(false));
  }, [selectedId, fetchUserRoles]);

  const filteredUsers = users.filter((u) => {
    if (!search.trim()) 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 selected = users.find((u) => u.id === selectedId);

  return (
    <div className="space-y-6 animate-in fade-in duration-500">
      <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-3">
        <div>
          <h1 className="text-3xl font-black text-text tracking-tight">Auxiliary Roles & Class Covers</h1>
          <p className="text-sm text-text-muted mt-1">
            Grant app-wide roles, scoped class covers, or temporary teacher assignments.
          </p>
        </div>
        {selectedId && (
          <div className="flex gap-2">
            <button
              onClick={() => { setFormMode('auxiliary'); setShowForm(true); }}
              className="inline-flex items-center gap-1.5 px-4 py-2 rounded-xl text-sm font-bold bg-primary text-white shadow"
            >
              <Shield size={14} /> Auxiliary Role
            </button>
            <button
              onClick={() => { setFormMode('cover'); setShowForm(true); }}
              className="inline-flex items-center gap-1.5 px-4 py-2 rounded-xl text-sm font-bold bg-card border border-border text-text hover:bg-background-alt"
            >
              <UserPlus size={14} /> Class Cover
            </button>
          </div>
        )}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* User list */}
        <div className="bg-card border border-border rounded-2xl overflow-hidden">
          <div className="p-3 border-b border-border">
            <div className="relative">
              <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted" />
              <input
                type="text"
                placeholder="Search users…"
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                className="w-full pl-9 pr-3 py-2 rounded-xl border border-border bg-background text-text text-sm"
              />
            </div>
          </div>
          <div className="max-h-[60vh] overflow-y-auto">
            {filteredUsers.length === 0 ? (
              <div className="p-6 text-center text-text-muted text-sm">No users match.</div>
            ) : (
              filteredUsers.map((u) => (
                <button
                  key={u.id}
                  onClick={() => setSelectedId(u.id)}
                  className={`w-full text-left px-4 py-3 border-b border-border/50 hover:bg-background-alt ${
                    selectedId === u.id ? 'bg-primary/5' : ''
                  }`}
                >
                  <div className="font-bold text-text text-sm">{u.first_name} {u.last_name}</div>
                  <div className="text-xs text-text-muted">{u.email}</div>
                  <div className="mt-1">
                    <RoleBadge role={u.role} size="sm" />
                  </div>
                </button>
              ))
            )}
          </div>
        </div>

        {/* Grant list */}
        <div className="lg:col-span-2 bg-card border border-border rounded-2xl p-6">
          {!selectedId ? (
            <div className="text-center text-text-muted py-12">
              Pick a user on the left to see their auxiliary role grants.
            </div>
          ) : loading ? (
            <div className="text-center text-text-muted py-12">Loading…</div>
          ) : (
            <>
              <div className="mb-4">
                <h2 className="text-lg font-black text-text">
                  {selected?.first_name} {selected?.last_name}
                </h2>
                <p className="text-xs text-text-muted">{selected?.email}</p>
                <div className="mt-2"><RoleBadge role={selected?.role} /></div>
              </div>
              {grants.length === 0 ? (
                <div className="text-center text-text-muted py-8">
                  No auxiliary role grants yet. Use the buttons above to grant one.
                </div>
              ) : (
                <div className="space-y-2">
                  {grants.map((g) => {
                    const active = !g.revoked_at && !isExpired(g.expires_at);
                    return (
                      <div
                        key={g.id}
                        className={`p-4 rounded-xl border ${
                          active
                            ? 'border-border bg-background'
                            : 'border-border/50 bg-background/40 opacity-60'
                        }`}
                      >
                        <div className="flex items-start justify-between gap-2">
                          <div className="flex-1 min-w-0">
                            <div className="flex items-center gap-2 mb-1">
                              <span className="font-bold text-text text-sm uppercase tracking-wider">
                                {g.role}
                              </span>
                              {g.scope_class_id && (
                                <span className="text-xs px-2 py-0.5 rounded-full bg-blue-500/10 text-blue-500 font-bold">
                                  Class: {g.scope_class_name || `#${g.scope_class_id}`}
                                </span>
                              )}
                              {!active && (
                                <span className="text-xs px-2 py-0.5 rounded-full bg-rose-500/10 text-rose-500 font-bold">
                                  {g.revoked_at ? 'Revoked' : 'Expired'}
                                </span>
                              )}
                            </div>
                            {g.reason && <div className="text-xs text-text-muted mb-1">📝 {g.reason}</div>}
                            <div className="text-xs text-text-muted flex items-center gap-1">
                              <Clock size={11} />
                              {fmt(g.starts_at)} → {g.expires_at ? fmt(g.expires_at) : 'no expiry'}
                            </div>
                          </div>
                          {active && (
                            <button
                              onClick={() => {
                                if (confirm(`Revoke the ${g.role} role${g.scope_class_id ? ' for this class' : ''}?`)) {
                                  revokeGrant(g.id, 'Revoked from UserRoles page').then(() => {
                                    fetchUserRoles(selectedId).then(setGrants);
                                  });
                                }
                              }}
                              className="p-2 rounded-lg text-rose-500 hover:bg-rose-500/10"
                              title="Revoke"
                            >
                              <Trash2 size={14} />
                            </button>
                          )}
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}
            </>
          )}
        </div>
      </div>

      {showForm && selectedId && (
        <CoverAssignmentForm
          mode={formMode}
          fixedUserId={selectedId}
          onClose={() => setShowForm(false)}
          onGranted={() => {
            fetchUserRoles(selectedId).then(setGrants);
          }}
        />
      )}
    </div>
  );
}
