'use client';

import { useState, useEffect, useCallback } from 'react';
import {
  Users,
  Plus,
  Search,
  Edit,
  Trash2,
  Lock,
  Unlock,
  Mail,
  Shield,
  Calendar,
} from 'lucide-react';
import { usersAPI, statsAPI, positionsAPI, userRolesAPI, permissionGroupsAPI } from '@/lib/api/admin';
import { employeesAPI } from '@/lib/api/employees';
import type { User, CreateUserData, UpdateUserData } from '@/lib/api/admin';
import type { Employee } from '@/lib/api/employees';
import Modal from '@/components/Modal';
import LoadingSpinner from '@/components/LoadingSpinner';

export default function UsersManagement() {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize] = useState(20);
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedRole, setSelectedRole] = useState<string>('');
  const [selectedStatus, setSelectedStatus] = useState<string>('');
  const [stats, setStats] = useState({ totalUsers: 0, activeUsers: 0, inactiveUsers: 0, loginsToday: 0 });
  const [positions, setPositions] = useState<{ id: string; title: string; titleAr?: string | null }[]>([]);
  const [employees, setEmployees] = useState<Employee[]>([]);
  const [showAddModal, setShowAddModal] = useState(false);
  const [showEditModal, setShowEditModal] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [saving, setSaving] = useState(false);
  const [deleteConfirm, setDeleteConfirm] = useState<string | null>(null);

  const fetchUsers = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await usersAPI.getAll({
        search: searchTerm || undefined,
        status: selectedStatus === 'active' ? 'active' : selectedStatus === 'inactive' ? 'inactive' : undefined,
        positionId: selectedRole || undefined,
        page,
        pageSize,
      });
      setUsers(res.data);
      setTotal(res.pagination.total);
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'فشل تحميل المستخدمين');
    } finally {
      setLoading(false);
    }
  }, [searchTerm, selectedRole, selectedStatus, page, pageSize]);

  const fetchStats = useCallback(async () => {
    try {
      const s = await statsAPI.get();
      setStats(s);
    } catch {
      // ignore
    }
  }, []);

  const fetchPositions = useCallback(async () => {
    try {
      const pos = await positionsAPI.getAll();
      setPositions(pos.map((p) => ({ id: p.id, title: p.title, titleAr: p.titleAr })));
    } catch {
      // ignore
    }
  }, []);

  const fetchEmployees = useCallback(async () => {
    try {
      const res = await employeesAPI.getAll({ status: 'ACTIVE', pageSize: 500 });
      setEmployees(res.employees);
    } catch {
      setEmployees([]);
    }
  }, []);

  useEffect(() => {
    fetchUsers();
  }, [fetchUsers]);

  useEffect(() => {
    fetchStats();
    fetchPositions();
  }, [fetchStats, fetchPositions]);

  useEffect(() => {
    if (showAddModal || showEditModal) fetchEmployees();
  }, [showAddModal, showEditModal, fetchEmployees]);

  const handleToggleActive = async (id: string) => {
    try {
      await usersAPI.toggleActive(id);
      fetchUsers();
      fetchStats();
    } catch (err: unknown) {
      alert(err instanceof Error ? err.message : 'فشل تحديث الحالة');
    }
  };

  const handleDelete = async (id: string) => {
    if (deleteConfirm !== id) return;
    try {
      await usersAPI.delete(id);
      setDeleteConfirm(null);
      fetchUsers();
      fetchStats();
    } catch (err: unknown) {
      alert(err instanceof Error ? err.message : 'فشل حذف المستخدم');
    }
  };

  const formatDate = (d: string | null | undefined) =>
    d ? new Date(d).toLocaleString('ar-SA', { dateStyle: 'short', timeStyle: 'short' }) : '-';

  const getFullName = (u: User) =>
    u.employee
      ? `${u.employee.firstName} ${u.employee.lastName}`.trim() ||
        `${u.employee.firstNameAr || ''} ${u.employee.lastNameAr || ''}`.trim() ||
        u.username
      : u.username;

  const getRole = (u: User) =>
    u.employee?.position?.titleAr || u.employee?.position?.title || '-';

  return (
    <div>
      <div className="mb-8 flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-gray-900 mb-2">إدارة المستخدمين</h1>
          <p className="text-gray-600">إدارة حسابات المستخدمين وصلاحياتهم</p>
        </div>
        <button
          onClick={() => setShowAddModal(true)}
          className="flex items-center gap-2 px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-all shadow-md hover:shadow-lg"
        >
          <Plus className="h-5 w-5" />
          <span className="font-semibold">إضافة مستخدم</span>
        </button>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
        {[
          { label: 'إجمالي المستخدمين', value: String(stats.totalUsers), color: 'bg-blue-500' },
          { label: 'المستخدمون النشطون', value: String(stats.activeUsers), color: 'bg-green-500' },
          { label: 'المستخدمون المعطلون', value: String(stats.inactiveUsers), color: 'bg-red-500' },
          { label: 'تسجيل دخول اليوم', value: String(stats.loginsToday), color: 'bg-purple-500' },
        ].map((stat, index) => (
          <div key={index} className="bg-white rounded-xl shadow-md p-6 border border-gray-100">
            <div className={`${stat.color} w-12 h-12 rounded-lg flex items-center justify-center mb-3`}>
              <Users className="h-6 w-6 text-white" />
            </div>
            <h3 className="text-2xl font-bold text-gray-900 mb-1">{stat.value}</h3>
            <p className="text-sm text-gray-600">{stat.label}</p>
          </div>
        ))}
      </div>

      {/* Filters */}
      <div className="bg-white rounded-xl shadow-md p-6 mb-8 border border-gray-100">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div className="relative">
            <Search className="absolute right-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
            <input
              type="text"
              placeholder="بحث بالاسم أو البريد..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              onKeyDown={(e) => e.key === 'Enter' && fetchUsers()}
              className="w-full pr-10 pl-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
          </div>
          <select
            value={selectedRole}
            onChange={(e) => setSelectedRole(e.target.value)}
            className="px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          >
            <option value="">جميع الأدوار</option>
            {positions.map((p) => (
              <option key={p.id} value={p.id}>
                {p.titleAr || p.title}
              </option>
            ))}
          </select>
          <select
            value={selectedStatus}
            onChange={(e) => setSelectedStatus(e.target.value)}
            className="px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          >
            <option value="">جميع الحالات</option>
            <option value="active">نشط</option>
            <option value="inactive">معطل</option>
          </select>
        </div>
        <button
          onClick={() => fetchUsers()}
          className="mt-4 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 text-sm font-medium"
        >
          بحث
        </button>
      </div>

      {/* Users Table */}
      <div className="bg-white rounded-xl shadow-md border border-gray-100 overflow-hidden">
        {loading ? (
          <div className="p-12 flex justify-center">
            <LoadingSpinner />
          </div>
        ) : error ? (
          <div className="p-12 text-center text-red-600">{error}</div>
        ) : (
          <>
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead className="bg-gray-50 border-b border-gray-200">
                  <tr>
                    <th className="px-6 py-4 text-right text-sm font-semibold text-gray-900">المستخدم</th>
                    <th className="px-6 py-4 text-right text-sm font-semibold text-gray-900">البريد الإلكتروني</th>
                    <th className="px-6 py-4 text-right text-sm font-semibold text-gray-900">الدور</th>
                    <th className="px-6 py-4 text-right text-sm font-semibold text-gray-900">الحالة</th>
                    <th className="px-6 py-4 text-right text-sm font-semibold text-gray-900">آخر تسجيل دخول</th>
                    <th className="px-6 py-4 text-right text-sm font-semibold text-gray-900">الإجراءات</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-200">
                  {users.map((user) => (
                    <tr key={user.id} className="hover:bg-gray-50 transition-colors">
                      <td className="px-6 py-4">
                        <div className="flex items-center gap-3">
                          <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-purple-600 rounded-full flex items-center justify-center text-white font-bold">
                            {getFullName(user).charAt(0)}
                          </div>
                          <div>
                            <p className="font-semibold text-gray-900">{getFullName(user)}</p>
                            <p className="text-sm text-gray-600">@{user.username}</p>
                          </div>
                        </div>
                      </td>
                      <td className="px-6 py-4">
                        <div className="flex items-center gap-2 text-gray-700">
                          <Mail className="h-4 w-4 text-gray-400" />
                          <span className="text-sm">{user.email}</span>
                        </div>
                      </td>
                      <td className="px-6 py-4">
                        <div className="flex items-center gap-2">
                          <Shield className="h-4 w-4 text-purple-500" />
                          <span className="text-sm font-medium text-gray-900">{getRole(user)}</span>
                        </div>
                      </td>
                      <td className="px-6 py-4">
                        {user.isActive ? (
                          <span className="inline-flex items-center gap-1 px-3 py-1 bg-green-100 text-green-800 rounded-full text-sm font-medium">
                            <div className="w-2 h-2 bg-green-500 rounded-full"></div>
                            نشط
                          </span>
                        ) : (
                          <span className="inline-flex items-center gap-1 px-3 py-1 bg-red-100 text-red-800 rounded-full text-sm font-medium">
                            <div className="w-2 h-2 bg-red-500 rounded-full"></div>
                            معطل
                          </span>
                        )}
                      </td>
                      <td className="px-6 py-4">
                        <div className="flex items-center gap-2 text-gray-600">
                          <Calendar className="h-4 w-4 text-gray-400" />
                          <span className="text-sm">{formatDate(user.lastLogin)}</span>
                        </div>
                      </td>
                      <td className="px-6 py-4">
                        <div className="flex items-center gap-2">
                          <button
                            onClick={() => {
                              setEditingUser(user);
                              setShowEditModal(true);
                            }}
                            className="p-2 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
                            title="تعديل"
                          >
                            <Edit className="h-4 w-4" />
                          </button>
                          <button
                            onClick={() => handleToggleActive(user.id)}
                            className="p-2 text-orange-600 hover:bg-orange-50 rounded-lg transition-colors"
                            title={user.isActive ? 'تعطيل' : 'تفعيل'}
                          >
                            {user.isActive ? <Lock className="h-4 w-4" /> : <Unlock className="h-4 w-4" />}
                          </button>
                          {deleteConfirm === user.id ? (
                            <div className="flex gap-1">
                              <button
                                onClick={() => handleDelete(user.id)}
                                className="px-2 py-1 text-xs bg-red-600 text-white rounded hover:bg-red-700"
                              >
                                تأكيد
                              </button>
                              <button
                                onClick={() => setDeleteConfirm(null)}
                                className="px-2 py-1 text-xs border border-gray-300 rounded hover:bg-gray-50"
                              >
                                إلغاء
                              </button>
                            </div>
                          ) : (
                            <button
                              onClick={() => setDeleteConfirm(user.id)}
                              className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                              title="حذف"
                            >
                              <Trash2 className="h-4 w-4" />
                            </button>
                          )}
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            {/* Pagination */}
            <div className="px-6 py-4 border-t border-gray-200 flex items-center justify-between">
              <p className="text-sm text-gray-600">
                عرض{' '}
                <span className="font-semibold">
                  {users.length ? (page - 1) * pageSize + 1 : 0}-{Math.min(page * pageSize, total)}
                </span>{' '}
                من <span className="font-semibold">{total}</span> مستخدم
              </p>
              <div className="flex gap-2">
                <button
                  onClick={() => setPage((p) => Math.max(1, p - 1))}
                  disabled={page <= 1}
                  className="px-4 py-2 border border-gray-300 rounded-lg text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  السابق
                </button>
                {Array.from({ length: Math.min(5, Math.ceil(total / pageSize) || 1) }, (_, i) => i + 1).map(
                  (n) => (
                    <button
                      key={n}
                      onClick={() => setPage(n)}
                      className={`px-4 py-2 rounded-lg text-sm font-medium ${
                        page === n
                          ? 'bg-blue-600 text-white'
                          : 'border border-gray-300 text-gray-700 hover:bg-gray-50'
                      }`}
                    >
                      {n}
                    </button>
                  )
                )}
                <button
                  onClick={() => setPage((p) => Math.min(Math.ceil(total / pageSize) || 1, p + 1))}
                  disabled={page >= Math.ceil(total / pageSize)}
                  className="px-4 py-2 border border-gray-300 rounded-lg text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  التالي
                </button>
              </div>
            </div>
          </>
        )}
      </div>

      {/* Add User Modal */}
      <AddUserModal
        isOpen={showAddModal}
        onClose={() => setShowAddModal(false)}
        onSuccess={() => {
          setShowAddModal(false);
          fetchUsers();
          fetchStats();
        }}
        employees={employees}
        saving={saving}
        setSaving={setSaving}
      />

      {/* Edit User Modal */}
      <EditUserModal
        isOpen={showEditModal}
        user={editingUser}
        onClose={() => {
          setShowEditModal(false);
          setEditingUser(null);
        }}
        onSuccess={() => {
          setShowEditModal(false);
          setEditingUser(null);
          fetchUsers();
          fetchStats();
        }}
        employees={employees}
        saving={saving}
        setSaving={setSaving}
      />

    </div>
  );
}

function AddUserModal({
  isOpen,
  onClose,
  onSuccess,
  employees,
  saving,
  setSaving,
}: {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
  employees: Employee[];
  saving: boolean;
  setSaving: (v: boolean) => void;
}) {
  const [form, setForm] = useState<CreateUserData & { isActive: boolean }>({
    email: '',
    username: '',
    password: '',
    employeeId: '',
    isActive: true,
  });

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!form.email || !form.username || !form.password || !form.employeeId) {
      alert('يرجى ملء جميع الحقول المطلوبة');
      return;
    }
    if (form.password.length < 8) {
      alert('كلمة المرور يجب أن تكون 8 أحرف على الأقل');
      return;
    }
    setSaving(true);
    try {
      await usersAPI.create(form);
      onSuccess();
    } catch (err: unknown) {
      const msg = (err as { response?: { data?: { message?: string } } })?.response?.data?.message || 'فشل إنشاء المستخدم';
      alert(msg);
    } finally {
      setSaving(false);
    }
  };

  return (
    <Modal isOpen={isOpen} onClose={onClose} title="إضافة مستخدم جديد" size="lg">
      <form onSubmit={handleSubmit} className="space-y-4">
        <div>
          <label className="block text-sm font-semibold text-gray-700 mb-2">الموظف المرتبط *</label>
          <select
            value={form.employeeId}
            onChange={(e) => {
              const emp = employees.find((em) => em.id === e.target.value);
              setForm((f) => ({
                ...f,
                employeeId: e.target.value,
                email: emp?.email || f.email,
                username: emp ? `${emp.firstName}.${emp.lastName}`.toLowerCase().replace(/\s/g, '.') : f.username,
              }));
            }}
            required
            className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
          >
            <option value="">اختر الموظف</option>
            {employees.map((emp) => (
              <option key={emp.id} value={emp.id}>
                {emp.firstName} {emp.lastName} - {emp.uniqueEmployeeId}
              </option>
            ))}
          </select>
        </div>
        <div>
          <label className="block text-sm font-semibold text-gray-700 mb-2">اسم المستخدم *</label>
          <input
            type="text"
            value={form.username}
            onChange={(e) => setForm((f) => ({ ...f, username: e.target.value }))}
            required
            className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
            placeholder="ahmed.mohamed"
          />
        </div>
        <div>
          <label className="block text-sm font-semibold text-gray-700 mb-2">البريد الإلكتروني *</label>
          <input
            type="email"
            value={form.email}
            onChange={(e) => setForm((f) => ({ ...f, email: e.target.value }))}
            required
            className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
            placeholder="ahmed@example.com"
          />
        </div>
        <div>
          <label className="block text-sm font-semibold text-gray-700 mb-2">كلمة المرور *</label>
          <input
            type="password"
            value={form.password}
            onChange={(e) => setForm((f) => ({ ...f, password: e.target.value }))}
            required
            minLength={8}
            className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
            placeholder="••••••••"
          />
        </div>
        <div className="flex items-center gap-2">
          <input
            type="checkbox"
            id="active"
            checked={form.isActive}
            onChange={(e) => setForm((f) => ({ ...f, isActive: e.target.checked }))}
            className="w-5 h-5 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
          />
          <label htmlFor="active" className="text-sm font-medium text-gray-700">
            تفعيل الحساب فوراً
          </label>
        </div>
        <div className="flex gap-3 justify-end pt-4">
          <button type="button" onClick={onClose} className="px-6 py-3 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 font-medium">
            إلغاء
          </button>
          <button type="submit" disabled={saving} className="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 font-semibold disabled:opacity-50">
            {saving ? 'جاري الحفظ...' : 'إنشاء المستخدم'}
          </button>
        </div>
      </form>
    </Modal>
  );
}

function EditUserModal({
  isOpen,
  user,
  onClose,
  onSuccess,
  employees,
  saving,
  setSaving,
}: {
  isOpen: boolean;
  user: User | null;
  onClose: () => void;
  onSuccess: () => void;
  employees: Employee[];
  saving: boolean;
  setSaving: (v: boolean) => void;
}) {
  const [form, setForm] = useState<UpdateUserData & { isActive?: boolean }>({
    email: '',
    username: '',
    password: '',
    employeeId: null,
    isActive: true,
  });
  const [userRoles, setUserRoles] = useState<{ id: string; role: { id: string; name: string; nameAr?: string | null } }[]>([]);
  const [permissionGroups, setPermissionGroups] = useState<{ id: string; name: string; nameAr?: string | null }[]>([]);
  const [assignRoleId, setAssignRoleId] = useState('');
  const [rolesLoading, setRolesLoading] = useState(false);

  useEffect(() => {
    if (user) {
      setForm({
        email: user.email,
        username: user.username,
        password: '',
        employeeId: user.employeeId ?? undefined,
        isActive: user.isActive,
      });
    }
  }, [user]);

  useEffect(() => {
    if (isOpen && user) {
      userRolesAPI.getAll(user.id).then((r) => setUserRoles(r)).catch(() => setUserRoles([]));
      permissionGroupsAPI.getAll().then((g) => setPermissionGroups(g)).catch(() => setPermissionGroups([]));
    }
  }, [isOpen, user?.id]);

  const handleAssignRole = async () => {
    if (!user || !assignRoleId) return;
    setRolesLoading(true);
    try {
      await userRolesAPI.assign(user.id, assignRoleId);
      const updated = await userRolesAPI.getAll(user.id);
      setUserRoles(updated);
      setAssignRoleId('');
    } catch (err: unknown) {
      alert(err instanceof Error ? err.message : 'فشل الإضافة');
    } finally {
      setRolesLoading(false);
    }
  };

  const handleRemoveRole = async (roleId: string) => {
    if (!user) return;
    setRolesLoading(true);
    try {
      await userRolesAPI.remove(user.id, roleId);
      setUserRoles((prev) => prev.filter((ur) => ur.role.id !== roleId));
    } catch (err: unknown) {
      alert(err instanceof Error ? err.message : 'فشل الإزالة');
    } finally {
      setRolesLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!user) return;
    if (!form.email || !form.username) {
      alert('يرجى ملء الحقول المطلوبة');
      return;
    }
    setSaving(true);
    try {
      const data: UpdateUserData = {
        email: form.email,
        username: form.username,
        isActive: form.isActive,
        employeeId: form.employeeId === '' ? null : form.employeeId || undefined,
      };
      if (form.password?.length && form.password.length >= 8) {
        data.password = form.password;
      }
      await usersAPI.update(user.id, data);
      onSuccess();
    } catch (err: unknown) {
      const msg = (err as { response?: { data?: { message?: string } } })?.response?.data?.message || 'فشل تحديث المستخدم';
      alert(msg);
    } finally {
      setSaving(false);
    }
  };

  return (
    <Modal isOpen={isOpen} onClose={onClose} title="تعديل المستخدم" size="lg">
      {user ? (
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">الموظف المرتبط</label>
            <select
              value={form.employeeId || ''}
              onChange={(e) => setForm((f) => ({ ...f, employeeId: e.target.value || null }))}
              className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
            >
              <option value="">-- بدون موظف --</option>
              {employees.map((emp) => (
                <option key={emp.id} value={emp.id}>
                  {emp.firstName} {emp.lastName} - {emp.uniqueEmployeeId}
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">اسم المستخدم *</label>
            <input
              type="text"
              value={form.username}
              onChange={(e) => setForm((f) => ({ ...f, username: e.target.value }))}
              required
              className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
            />
          </div>
          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">البريد الإلكتروني *</label>
            <input
              type="email"
              value={form.email}
              onChange={(e) => setForm((f) => ({ ...f, email: e.target.value }))}
              required
              className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
            />
          </div>
          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">كلمة مرور جديدة (اختياري)</label>
            <input
              type="password"
              value={form.password || ''}
              onChange={(e) => setForm((f) => ({ ...f, password: e.target.value || undefined }))}
              minLength={8}
              className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
              placeholder="اتركه فارغاً للإبقاء على كلمة المرور الحالية"
            />
          </div>
          <div className="flex items-center gap-2">
            <input
              type="checkbox"
              id="edit-active"
              checked={form.isActive ?? true}
              onChange={(e) => setForm((f) => ({ ...f, isActive: e.target.checked }))}
              className="w-5 h-5 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
            />
            <label htmlFor="edit-active" className="text-sm font-medium text-gray-700">
              الحساب نشط
            </label>
          </div>
          <div className="border-t pt-4 mt-4">
            <label className="block text-sm font-semibold text-gray-700 mb-2">مجموعات الصلاحيات الإضافية</label>
            <p className="text-xs text-gray-600 mb-2">صلاحيات اختيارية تضاف إلى صلاحيات الوظيفة</p>
            <div className="flex gap-2 mb-3">
              <select
                value={assignRoleId}
                onChange={(e) => setAssignRoleId(e.target.value)}
                className="flex-1 px-4 py-2 border border-gray-300 rounded-lg"
              >
                <option value="">إضافة مجموعة...</option>
                {permissionGroups
                  .filter((g) => !userRoles.some((ur) => ur.role.id === g.id))
                  .map((g) => (
                    <option key={g.id} value={g.id}>{g.nameAr || g.name}</option>
                  ))}
              </select>
              <button
                type="button"
                onClick={handleAssignRole}
                disabled={!assignRoleId || rolesLoading}
                className="px-4 py-2 bg-blue-100 text-blue-700 rounded-lg hover:bg-blue-200 disabled:opacity-50"
              >
                إضافة
              </button>
            </div>
            <div className="space-y-2">
              {userRoles.map((ur) => (
                <div key={ur.id} className="flex items-center justify-between py-2 px-3 bg-gray-50 rounded-lg">
                  <span className="font-medium">{ur.role.nameAr || ur.role.name}</span>
                  <button
                    type="button"
                    onClick={() => handleRemoveRole(ur.role.id)}
                    disabled={rolesLoading}
                    className="text-red-600 hover:text-red-700 text-sm disabled:opacity-50"
                  >
                    إزالة
                  </button>
                </div>
              ))}
              {userRoles.length === 0 && (
                <p className="text-sm text-gray-500 py-2">لا توجد مجموعات إضافية</p>
              )}
            </div>
          </div>
          <div className="flex gap-3 justify-end pt-4">
            <button type="button" onClick={onClose} className="px-6 py-3 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 font-medium">
              إلغاء
            </button>
            <button type="submit" disabled={saving} className="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 font-semibold disabled:opacity-50">
              {saving ? 'جاري الحفظ...' : 'حفظ التغييرات'}
            </button>
          </div>
        </form>
      ) : (
        <LoadingSpinner />
      )}
    </Modal>
  );
}
