import { useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { UserCog, Plus } from 'lucide-react'
import { getUsers, createUser, updateUserRole, updateUserActive, resetPassword, deleteUser } from '../api/client'

const ROLES = ['USER', 'MANAGER', 'ADMIN']

export default function UserManagement() {
  const qc = useQueryClient()
  const { data: users } = useQuery({ queryKey: ['users'], queryFn: getUsers })
  const [nu, setNu] = useState({ username: '', password: '', role: 'USER' })
  const [open, setOpen] = useState(false)

  const refresh = () => qc.invalidateQueries({ queryKey: ['users'] })
  const add = async () => { if (!nu.username || !nu.password) return; await createUser(nu).catch(() => {}); setNu({ username: '', password: '', role: 'USER' }); setOpen(false); refresh() }
  const setRole = async (id: number, role: string) => { await updateUserRole(id, role).catch(() => {}); refresh() }
  const toggleActive = async (id: number, active: boolean) => { await updateUserActive(id, !active).catch(() => {}); refresh() }
  const reset = async (id: number) => { const pw = prompt('New password'); if (pw) { await resetPassword(id, pw).catch(() => {}); alert('Password updated') } }
  const del = async (id: number) => { if (confirm('Are you sure you want to delete?')) { await deleteUser(id).catch(() => {}); refresh() } }

  return (
    <div>
      <div className="flex items-center justify-between mb-5">
        <div className="flex items-center gap-2"><UserCog className="text-brand" size={22} /><h1 className="text-xl font-bold">User Management (RBAC)</h1></div>
        <button onClick={() => setOpen(!open)} className="flex items-center gap-1.5 bg-brand text-ink text-sm font-semibold px-3 py-2 rounded-lg"><Plus size={15} /> Add User</button>
      </div>

      {open && (
        <div className="bg-card border border-edge rounded-xl p-5 mb-5 grid grid-cols-4 gap-3">
          <input value={nu.username} onChange={e => setNu({ ...nu, username: e.target.value })} placeholder="Username" className="bg-panel border border-edge rounded-lg px-3 py-2 text-sm" />
          <input type="password" value={nu.password} onChange={e => setNu({ ...nu, password: e.target.value })} placeholder="Password" className="bg-panel border border-edge rounded-lg px-3 py-2 text-sm" />
          <select value={nu.role} onChange={e => setNu({ ...nu, role: e.target.value })} className="bg-panel border border-edge rounded-lg px-3 py-2 text-sm">{ROLES.map(r => <option key={r}>{r}</option>)}</select>
          <button onClick={add} className="bg-brand text-ink font-semibold rounded-lg px-3 py-2 text-sm">Create</button>
        </div>
      )}

      <div className="bg-card border border-edge rounded-xl overflow-hidden">
        <table className="w-full text-sm">
          <thead><tr className="text-slate-400 text-xs border-b border-edge bg-panel">
            <th className="text-left p-3">ID</th><th className="text-left">Username</th><th className="text-left">Role</th><th className="text-center">Status</th><th className="text-center">Actions</th>
          </tr></thead>
          <tbody>
            {(users || []).map((u: any) => (
              <tr key={u.id} className="border-b border-edge/50 hover:bg-panel/50">
                <td className="p-3 text-slate-400">{u.id}</td>
                <td>{u.username}</td>
                <td>
                  <select value={u.role} onChange={e => setRole(u.id, e.target.value)} className="bg-panel border border-edge rounded px-2 py-1 text-xs">{ROLES.map(r => <option key={r}>{r}</option>)}</select>
                </td>
                <td className="text-center">
                  <button onClick={() => toggleActive(u.id, u.active)} className={`px-2 py-1 rounded text-xs ${u.active !== false ? 'bg-emerald-500/15 text-emerald-400' : 'bg-slate-600/20 text-slate-400'}`}>{u.active !== false ? 'Active' : 'Inactive'}</button>
                </td>
                <td className="text-center">
                  <div className="inline-flex gap-1">
                    <button onClick={() => reset(u.id)} className="text-xs bg-panel border border-edge px-2 py-1 rounded text-slate-300">Password</button>
                    <button onClick={() => del(u.id)} className="text-xs bg-rose-500/15 text-rose-400 px-2 py-1 rounded">Delete</button>
                  </div>
                </td>
              </tr>
            ))}
            {!(users || []).length && <tr><td colSpan={5} className="text-center text-slate-500 py-8">No users found.</td></tr>}
          </tbody>
        </table>
      </div>
    </div>
  )
}
