'use client';
import { useState, useEffect } from 'react';
import { Plus, Pencil, Trash2, Loader2, Users as UsersIcon } from 'lucide-react';
import api from '@/lib/api';
import toast from 'react-hot-toast';

const ROLES = ['super_admin','admin','editor','author','moderator','reader'];
const STATUSES = ['active','inactive','banned'];

const roleChip = (r: string) => ({
  super_admin: 'bg-brand-900 text-white',
  admin: 'bg-brand-100 text-brand-800 dark:bg-brand-900/40 dark:text-brand-200',
  editor: 'bg-brand-50 text-brand-700 dark:bg-brand-900/30 dark:text-brand-300',
  author: 'bg-brand-50 text-brand-700 dark:bg-brand-900/30 dark:text-brand-300',
  moderator: 'bg-brand-50 text-brand-700 dark:bg-brand-900/30 dark:text-brand-300',
  reader: 'bg-surface-sunken text-muted',
}[r] || 'bg-surface-sunken text-muted');

const statusChip = (s: string) => ({
  active: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300',
  inactive: 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300',
  banned: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300',
}[s] || 'bg-surface-sunken text-muted');

const inputClass = 'w-full rounded-md border border-surface bg-surface px-3 py-2 text-sm outline-none focus:border-brand-500';

export default function AdminUsers() {
  const [users, setUsers] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [modal, setModal] = useState(false);
  const [saving, setSaving] = useState(false);
  const [editing, setEditing] = useState<any>(null);
  const [form, setForm] = useState({ name: '', email: '', password: '', role: 'reader', status: 'active' });

  const fetchUsers = async () => {
    setLoading(true); setError('');
    try { const r = await api.get('/users', { params: { page, limit: 15 } }); setUsers(r.data.data || r.data.users || []); setTotal(r.data.meta?.total || r.data.total || 0); }
    catch { setError('Failed to load users.'); toast.error('Failed to load'); } finally { setLoading(false); }
  };
  useEffect(() => { fetchUsers(); }, [page]);

  const openNew = () => { setEditing(null); setForm({ name:'',email:'',password:'',role:'reader',status:'active' }); setModal(true); };
  const openEdit = (u: any) => { setEditing(u); setForm({ name:u.name,email:u.email,password:'',role:u.role,status:u.status }); setModal(true); };

  const handleSave = async () => {
    if (!form.name||!form.email) return toast.error('Name and email required');
    setSaving(true);
    try {
      const payload = { ...form };
      if (editing) { if (!payload.password) delete (payload as any).password; await api.put(`/users/${editing.id}`, payload); }
      else { if (!payload.password) { setSaving(false); return toast.error('Password required'); } await api.post('/users', payload); }
      toast.success(editing?'Updated':'Created'); setModal(false); fetchUsers();
    } catch(e:any) { toast.error(e.response?.data?.message||'Error'); } finally { setSaving(false); }
  };

  const handleDelete = async (id: number) => {
    if (!confirm('Delete this user? This cannot be undone.')) return;
    try { await api.delete(`/users/${id}`); toast.success('Deleted'); fetchUsers(); }
    catch { toast.error('Delete failed'); }
  };

  const totalPages = Math.ceil(total/15);

  return (
    <div>
      <div className="mb-6 flex items-center justify-between">
        <div>
          <h1 className="font-serif text-2xl font-extrabold text-body">Users</h1>
          <p className="mt-1 text-sm text-muted">{total} total {total === 1 ? 'user' : 'users'}</p>
        </div>
        <button onClick={openNew} className="flex items-center gap-2 rounded-md bg-brand-900 px-4 py-2 text-sm font-semibold text-white transition hover:bg-brand-800"><Plus size={16}/> New User</button>
      </div>

      <div className="overflow-hidden rounded-card border border-surface bg-surface">
        {loading ? (
          <div className="flex items-center justify-center gap-2 p-12 text-muted"><Loader2 size={18} className="animate-spin"/> Loading users…</div>
        ) : error ? (
          <div className="p-12 text-center">
            <p className="text-sm text-red-600 dark:text-red-400">{error}</p>
            <button onClick={fetchUsers} className="mt-3 rounded-md border border-surface px-4 py-2 text-sm font-medium text-body hover:bg-surface-sunken">Retry</button>
          </div>
        ) : users.length === 0 ? (
          <div className="flex flex-col items-center gap-2 p-12 text-center text-muted">
            <UsersIcon size={28} className="text-muted"/>
            <p className="text-sm">No users found.</p>
          </div>
        ) : (
          <table className="w-full text-sm">
            <thead className="bg-surface-sunken text-xs uppercase tracking-wide text-muted"><tr><th className="px-4 py-3 text-left">Name</th><th className="px-4 py-3 text-left">Email</th><th className="px-4 py-3 text-left">Role</th><th className="px-4 py-3 text-left">Status</th><th className="px-4 py-3 text-right">Actions</th></tr></thead>
            <tbody className="divide-y divide-surface">
              {users.map((u:any) => (
                <tr key={u.id} className="hover:bg-surface-sunken/60">
                  <td className="px-4 py-3 font-medium text-body">{u.name}</td>
                  <td className="px-4 py-3 text-muted">{u.email}</td>
                  <td className="px-4 py-3"><span className={`inline-block rounded-full px-2 py-0.5 text-xs font-medium capitalize ${roleChip(u.role)}`}>{u.role.replace('_',' ')}</span></td>
                  <td className="px-4 py-3"><span className={`inline-block rounded-full px-2 py-0.5 text-xs font-medium capitalize ${statusChip(u.status)}`}>{u.status}</span></td>
                  <td className="px-4 py-3"><div className="flex items-center justify-end gap-1"><button onClick={() => openEdit(u)} title="Edit" className="rounded-md p-1.5 text-muted transition hover:bg-brand-50 hover:text-brand-700 dark:hover:bg-brand-900/30"><Pencil size={15}/></button><button onClick={() => handleDelete(u.id)} title="Delete" className="rounded-md p-1.5 text-muted transition hover:bg-red-50 hover:text-red-600 dark:hover:bg-red-900/30"><Trash2 size={15}/></button></div></td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
        {!loading && !error && totalPages>1 && <div className="flex justify-end gap-1 border-t border-surface px-4 py-3">{Array.from({length:totalPages},(_,i)=>i+1).map(p=>(<button key={p} onClick={()=>setPage(p)} className={`rounded-md px-3 py-1 text-xs font-medium transition ${p===page?'bg-brand-900 text-white':'bg-surface-sunken text-muted hover:bg-surface-sunken/70'}`}>{p}</button>))}</div>}
      </div>

      {modal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
          <div className="w-full max-w-md rounded-card border border-surface bg-surface p-6 shadow-xl">
            <h2 className="mb-4 font-serif text-lg font-bold text-body">{editing?'Edit User':'New User'}</h2>
            <div className="space-y-3">
              <input value={form.name} onChange={e=>setForm(f=>({...f,name:e.target.value}))} placeholder="Full name" className={inputClass} />
              <input value={form.email} onChange={e=>setForm(f=>({...f,email:e.target.value}))} type="email" placeholder="Email" className={inputClass} />
              <input value={form.password} onChange={e=>setForm(f=>({...f,password:e.target.value}))} type="password" placeholder={editing?'New password (leave blank to keep)':'Password'} className={inputClass} />
              <select value={form.role} onChange={e=>setForm(f=>({...f,role:e.target.value}))} className={inputClass}>{ROLES.map(r=><option key={r} value={r}>{r.replace('_',' ')}</option>)}</select>
              <select value={form.status} onChange={e=>setForm(f=>({...f,status:e.target.value}))} className={inputClass}>{STATUSES.map(s=><option key={s} value={s}>{s}</option>)}</select>
            </div>
            <div className="mt-5 flex justify-end gap-2">
              <button onClick={()=>setModal(false)} className="rounded-md border border-surface px-4 py-2 text-sm font-medium text-body transition hover:bg-surface-sunken">Cancel</button>
              <button onClick={handleSave} disabled={saving} className="flex items-center gap-2 rounded-md bg-brand-900 px-4 py-2 text-sm font-semibold text-white transition hover:bg-brand-800 disabled:opacity-60">{saving && <Loader2 size={14} className="animate-spin"/>}Save</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
