'use client'; import { useState } from 'react'; interface User { id: number; username: string; email: string; role: string; isPremium: boolean; firstName?: string; lastName?: string; createdAt: string; } interface ResetResult { to: string; subject: string; body: string; temporaryPassword: string; } interface Props { users: User[]; currentUserId: number; } export default function AnvandareClient({ users: initial, currentUserId }: Props) { const [users, setUsers] = useState(initial); const [error, setError] = useState(''); const [showCreate, setShowCreate] = useState(false); const [creating, setCreating] = useState(false); const [createForm, setCreateForm] = useState({ username: '', email: '', password: '', role: 'user', }); const [createError, setCreateError] = useState(''); // Lösenordsåterställning modal const [resetResult, setResetResult] = useState(null); const [copiedBody, setCopiedBody] = useState(false); const [copiedPw, setCopiedPw] = useState(false); // Inline e-postbyte const [editingEmailId, setEditingEmailId] = useState(null); const [editingEmail, setEditingEmail] = useState(''); async function handleCreate(e: React.FormEvent) { e.preventDefault(); setCreating(true); setCreateError(''); try { const res = await fetch('/api/admin-users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(createForm), }); const data = await res.json(); if (!res.ok) throw new Error(data.message ?? 'Kunde inte skapa användare'); setUsers((prev) => [...prev, data]); setShowCreate(false); setCreateForm({ username: '', email: '', password: '', role: 'user' }); } catch (err: any) { setCreateError(err.message); } finally { setCreating(false); } } async function handleDelete(id: number) { if (!confirm('Är du säker på att du vill ta bort användaren?')) return; setError(''); const res = await fetch(`/api/admin-users/${id}`, { method: 'DELETE' }); if (res.ok) { setUsers((prev) => prev.filter((u) => u.id !== id)); } else { const data = await res.json().catch(() => ({})); setError(data.message ?? 'Kunde inte ta bort användaren'); } } async function handleRoleChange(id: number, role: string) { setError(''); const res = await fetch(`/api/admin-users/${id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ role }), }); if (res.ok) { const updated = await res.json(); setUsers((prev) => prev.map((u) => (u.id === id ? { ...u, role: updated.role } : u))); } else { const data = await res.json().catch(() => ({})); setError(data.message ?? 'Kunde inte ändra roll'); } } async function handleResetPassword(id: number) { setError(''); const res = await fetch(`/api/admin-users/${id}/reset-password`, { method: 'POST' }); const data = await res.json(); if (!res.ok) { setError(data.message ?? 'Kunde inte återställa lösenord'); return; } setResetResult(data); setCopiedBody(false); setCopiedPw(false); } async function handlePremiumChange(id: number, isPremium: boolean) { setError(''); const res = await fetch(`/api/admin-users/${id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ isPremium }), }); if (res.ok) { setUsers((prev) => prev.map((u) => (u.id === id ? { ...u, isPremium } : u))); } else { const data = await res.json().catch(() => ({})); setError(data.message ?? 'Kunde inte ändra plan'); } } async function handleEmailSave(id: number) { setError(''); const res = await fetch(`/api/admin-users/${id}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: editingEmail }), }); if (res.ok) { const updated = await res.json(); setUsers((prev) => prev.map((u) => (u.id === id ? { ...u, email: updated.email } : u))); setEditingEmailId(null); } else { const data = await res.json().catch(() => ({})); setError(data.message ?? 'Kunde inte uppdatera e-post'); } } return (
{/* Lägg till användare */}
{showCreate && (

Ny användare

{createError && (
{createError}
)} {[ { key: 'username', label: 'Användarnamn', type: 'text' }, { key: 'email', label: 'E-post', type: 'email' }, { key: 'password', label: 'Lösenord', type: 'password' }, ].map(({ key, label, type }) => (
setCreateForm((f) => ({ ...f, [key]: e.target.value }))} required style={{ width: '100%', padding: '0.4rem 0.6rem', border: '1px solid #cbd5e1', borderRadius: 4, fontSize: 14, boxSizing: 'border-box', }} />
))}
)}
{error && (
{error}
)} {/* Användartabell */}
{['Användare', 'E-post', 'Roll', 'Plan', 'Åtgärder'].map((h) => ( ))} {users.map((user) => { const isSelf = user.id === currentUserId; const isEditingEmail = editingEmailId === user.id; return ( {/* Namn */} {/* E-post */} {/* Roll */} {/* Plan */} {/* Åtgärder */} ); })}
{h}
{user.username}
{(user.firstName || user.lastName) && (
{[user.firstName, user.lastName].filter(Boolean).join(' ')}
)} {isSelf && ( Du själv )}
{isEditingEmail ? (
setEditingEmail(e.target.value)} style={{ padding: '0.3rem 0.5rem', border: '1px solid #93c5fd', borderRadius: 4, fontSize: 13, width: 180, }} />
) : (
{user.email} {!isSelf && ( )}
)}
{isSelf ? ( ) : ( )} {isSelf ? ( ) : (
)}
{/* Lösenordsåterställning modal */} {resetResult && (

Lösenordet har återställts

Skicka nedanstående meddelande till användaren och/eller ge dem det tillfälliga lösenordet.