// [REQ F8]  Zarządzanie użytkownikami (admin) – dezaktywacja kont, reset hasła
// [REQ D6]  HOC – eksportowany przez withRole(['admin'])(UserManagementInner)
// [REQ D7]  React Query – useQuery + useMutation z invalidateQueries
import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { UserCheck, UserX, Shield, Mail, RefreshCw } from 'lucide-react';
import withRole from '../hocs/withRole';
import StatusBadge from './StatusBadge';
import { API_URL } from '../config';
import styles from './UserManagement.module.scss';

const fetchUsers = () =>
  fetch(`${API_URL}/users`).then((r) => r.json());

const patchUser = ({ id, patch }) =>
  fetch(`${API_URL}/users/${id}`, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(patch),
  }).then((r) => r.json());

const ROLES = ['client', 'admin'];

const UserManagementInner = () => {
  const qc = useQueryClient();
  const [editingRole, setEditingRole] = useState(null);

  const { data: users = [], isLoading, refetch } = useQuery({
    queryKey: ['users'],
    queryFn: fetchUsers,
  });

  const { mutate: updateUser, isPending } = useMutation({
    mutationFn: patchUser,
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['users'] });
      setEditingRole(null);
    },
  });

  const toggleActive = (user) => {
    updateUser({ id: user.id, patch: { active: !(user.active ?? true) } });
  };

  const changeRole = (user, role) => {
    updateUser({ id: user.id, patch: { role } });
  };

  if (isLoading) return <p className={styles['um__msg']}>Loading users…</p>;

  return (
    <div className={styles['um']}>
      <div className={styles['um__toolbar']}>
        <span className={styles['um__count']}>{users.length} users</span>
        <button className={styles['um__refresh']} onClick={() => refetch()} disabled={isPending}>
          <RefreshCw size={14} /> Refresh
        </button>
      </div>

      <div className={styles['um__table-wrap']}>
        <table className={styles['um__table']}>
          <thead>
            <tr>
              <th>Name</th>
              <th>Email</th>
              <th>Role</th>
              <th>Verified</th>
              <th>Status</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            {users.map((u) => {
              const isActive = u.active !== false;
              return (
                <tr key={u.id} className={isActive ? '' : styles['um__row--inactive']}>
                  <td>{u.name ?? '—'}</td>
                  <td className={styles['um__cell--email']}>
                    <Mail size={12} /> {u.email}
                  </td>
                  <td>
                    {editingRole === u.id ? (
                      <select
                        className={styles['um__role-select']}
                        defaultValue={u.role}
                        onChange={(e) => changeRole(u, e.target.value)}
                        onBlur={() => setEditingRole(null)}
                        autoFocus
                      >
                        {ROLES.map((r) => <option key={r} value={r}>{r}</option>)}
                      </select>
                    ) : (
                      <button
                        className={styles['um__role-btn']}
                        onClick={() => setEditingRole(u.id)}
                        title="Click to change role"
                      >
                        <Shield size={11} /> {u.role}
                      </button>
                    )}
                  </td>
                  <td>
                    <StatusBadge
                      status={u.verified !== false ? 'confirmed' : 'pending'}
                      size="sm"
                    />
                  </td>
                  <td>
                    <span className={[
                      styles['um__status'],
                      isActive ? styles['um__status--active'] : styles['um__status--inactive'],
                    ].join(' ')}>
                      {isActive ? 'Active' : 'Inactive'}
                    </span>
                  </td>
                  <td>
                    <button
                      className={[
                        styles['um__toggle'],
                        isActive ? styles['um__toggle--deactivate'] : styles['um__toggle--activate'],
                      ].join(' ')}
                      onClick={() => toggleActive(u)}
                      disabled={isPending}
                      title={isActive ? 'Deactivate account' : 'Activate account'}
                    >
                      {isActive ? <UserX size={14} /> : <UserCheck size={14} />}
                      {isActive ? 'Deactivate' : 'Activate'}
                    </button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
};

// Wrap with HOC — only admins can see user management
const UserManagement = withRole(['admin'])(UserManagementInner);
export default UserManagement;
