'use client';

import React, { useState, useEffect, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import AdminLayout from '@/components/admin/AdminLayout';
import Pagination from '@/components/admin/Pagination';

interface UserData {
  id: number; username: string; role: string;
  fullName: string | null; photo: string | null; createdAt: string;
}

export default function AdminUsersPage() {
  const router = useRouter();
  const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5000';
  const [users, setUsers] = useState<UserData[]>([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [form, setForm] = useState({ username: '', password: '', fullName: '', role: 'editor', newPassword: '', confirmPassword: '' });
  const [photoFile, setPhotoFile] = useState<File | null>(null);
  const [photoPreview, setPhotoPreview] = useState<string | null>(null);
  const [msg, setMsg] = useState('');
  const [msgType, setMsgType] = useState<'success'|'error'>('success');
  const [page, setPage] = useState(1);
  const perPage = 10;
  const totalPages = Math.max(1, Math.ceil(users.length / perPage));
  const paginatedUsers = useMemo(() => users.slice((page - 1) * perPage, page * perPage), [users, page]);

  useEffect(() => {
    const token = localStorage.getItem('admin_token');
    if (!token) { router.push('/admin/login'); return; }
    fetchUsers();
  }, [router]);

  const headers = () => ({ 'Authorization': `Bearer ${localStorage.getItem('admin_token')}` });

  const fetchUsers = async () => {
    try {
      const res = await fetch(`${apiUrl}/api/auth/users`, { headers: headers() });
      if (res.ok) setUsers(await res.json());
    } catch (e) {}
    finally { setLoading(false); }
  };

  const showMsg = (text: string, type: 'success'|'error' = 'success') => {
    setMsg(text); setMsgType(type); setTimeout(() => setMsg(''), 4000);
  };

  const openCreate = () => {
    setEditingId(null);
    setForm({ username: '', password: '', fullName: '', role: 'editor', newPassword: '', confirmPassword: '' });
    setPhotoFile(null); setPhotoPreview(null); setShowForm(true);
  };

  const openEdit = (u: UserData) => {
    setEditingId(u.id);
    setForm({ username: u.username, password: '', fullName: u.fullName || '', role: u.role, newPassword: '', confirmPassword: '' });
    setPhotoFile(null); setPhotoPreview(null); setShowForm(true);
  };

  const validatePassword = (pwd: string) => {
    if (!pwd) return true;
    if (pwd.length < 8) return false;
    if (!/[A-Z]/.test(pwd)) return false;
    if (!/[0-9]/.test(pwd)) return false;
    if (!/[!@#$%^&*(),.?":{}|<>_\-]/.test(pwd)) return false;
    return true;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault(); setMsg('');
    if (form.newPassword && form.newPassword !== form.confirmPassword) {
      showMsg('Konfirmasi password baru tidak sama dengan password baru', 'error'); return;
    }
    if (form.newPassword && !validatePassword(form.newPassword)) {
      showMsg('Password harus kombinasi huruf besar, angka, dan simbol', 'error'); return;
    }
    const formData = new FormData();
    formData.append('fullName', form.fullName);
    formData.append('role', form.role);
    if (photoFile) formData.append('photo', photoFile);
    if (editingId) {
      if (form.newPassword) formData.append('newPassword', form.newPassword);
      const res = await fetch(`${apiUrl}/api/auth/users/${editingId}`, { method: 'PUT', headers: { 'Authorization': `Bearer ${localStorage.getItem('admin_token')}` }, body: formData });
      const data = await res.json();
      if (res.ok) { showMsg(data.message); setShowForm(false); fetchUsers(); }
      else showMsg(data.message, 'error');
    } else {
      formData.append('username', form.username);
      formData.append('password', form.password);
      const res = await fetch(`${apiUrl}/api/auth/register`, { method: 'POST', headers: { 'Authorization': `Bearer ${localStorage.getItem('admin_token')}` }, body: formData });
      const data = await res.json();
      if (res.ok) { showMsg(data.message); setShowForm(false); fetchUsers(); }
      else showMsg(data.message, 'error');
    }
  };

  const handleDelete = async (id: number) => {
    if (!confirm('Hapus user ini?')) return;
    try {
      const res = await fetch(`${apiUrl}/api/auth/users/${id}`, { method: 'DELETE', headers: headers() });
      if (res.ok) fetchUsers();
      else { const d = await res.json(); showMsg(d.message, 'error'); }
    } catch (e) { showMsg('Gagal menghapus', 'error'); }
  };

  return (
    <AdminLayout title="Users">
      <div className="space-y-6">
        {msg && <div className={`p-3 rounded-lg text-sm flex items-center gap-2 ${msgType === 'success' ? 'bg-green-50 border border-green-100 text-green-600' : 'bg-red-50 border border-red-100 text-red-600'}`}><span>{msgType === 'success' ? '✅' : '❌'}</span>{msg}</div>}
        <div className="flex items-center justify-between">
          <p className="text-sm text-gray-500">{users.length} user terdaftar</p>
          <button onClick={openCreate} className="admin-btn-primary"><svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4"/></svg>Tambah User</button>
        </div>

        {showForm && (
          <div className="bg-white rounded-xl border border-gray-200 p-6">
            <h3 className="font-semibold text-gray-800 mb-4">{editingId ? 'Edit User' : 'Tambah User Baru'}</h3>
            <form onSubmit={handleSubmit} className="space-y-4 max-w-lg">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                <div><label className="admin-label">Username *</label><input type="text" value={form.username} onChange={(e) => setForm({ ...form, username: e.target.value })} required className="admin-input" /></div>
                <div><label className="admin-label">Nama Lengkap</label><input type="text" value={form.fullName} onChange={(e) => setForm({ ...form, fullName: e.target.value })} className="admin-input" /></div>
                {!editingId && (<div><label className="admin-label">Password *</label><input type="password" value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })} required className="admin-input" /><p className="text-xs text-gray-400 mt-1">Huruf besar + angka + simbol, min 8</p></div>)}
                <div><label className="admin-label">Role</label><select value={form.role} onChange={(e) => setForm({ ...form, role: e.target.value })} className="admin-select"><option value="admin">Admin</option><option value="editor">Editor</option></select></div>
              </div>
              {editingId && (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3 p-4 bg-gray-50 rounded-lg">
                  <p className="text-sm font-medium text-gray-600 md:col-span-2">🔑 Ganti Password (opsional)</p>
                  <div><label className="admin-label">Password Baru</label><input type="password" value={form.newPassword} onChange={(e) => setForm({ ...form, newPassword: e.target.value })} className="admin-input" /></div>
                  <div><label className="admin-label">Konfirmasi</label><input type="password" value={form.confirmPassword} onChange={(e) => setForm({ ...form, confirmPassword: e.target.value })} className="admin-input" /></div>
                </div>
              )}
              <div><label className="admin-label">Foto Profil (max 5MB, opsional)</label>
                  <label className="inline-flex items-center gap-2 px-4 py-2 bg-gold text-white text-xs font-semibold rounded-lg cursor-pointer hover:bg-gold-dark transition">
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"/></svg>
                    Pilih Foto
                    <input type="file" accept="image/*" onChange={(e) => { const f = e.target.files?.[0]; if (f) { setPhotoFile(f); setPhotoPreview(URL.createObjectURL(f)); } }} className="hidden" />
                  </label>
              {photoPreview && <img src={photoPreview} className="w-16 h-16 rounded-full object-cover mt-2 border" />}</div>
              <div className="flex gap-3 justify-end pt-2 border-t border-gray-100">
                <button type="button" onClick={() => setShowForm(false)} className="admin-btn-secondary">Batal</button>
                <button type="submit" className="admin-btn-primary">{editingId ? 'Simpan' : 'Tambah User'}</button>
              </div>
            </form>
          </div>
        )}

        {loading ? <p className="text-gray-400">Memuat...</p> : users.length === 0 ? (
          <div className="bg-white rounded-xl border border-gray-200 p-12 text-center"><p className="text-4xl mb-3">👤</p><p className="text-gray-500">Belum ada user</p></div>
        ) : (
          <>
            <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
              <table className="admin-table">
                <thead><tr><th>Nama</th><th>Username</th><th>Role</th><th className="text-right">Aksi</th></tr></thead>
                <tbody>{paginatedUsers.map((u) => (
                  <tr key={u.id}>
                    <td><div className="flex items-center gap-3"><div className="w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center overflow-hidden">{u.photo ? <img src={u.photo} className="w-full h-full object-cover" /> : <span className="text-sm font-semibold text-gray-500">{(u.fullName || u.username).charAt(0).toUpperCase()}</span>}</div><span className="font-medium text-gray-800">{u.fullName || u.username}</span></div></td>
                    <td className="text-gray-600">{u.username}</td>
                    <td><span className={`text-xs px-2 py-0.5 rounded-full font-medium ${u.role === 'admin' ? 'bg-gold/10 text-gold' : 'bg-blue-50 text-blue-600'}`}>{u.role}</span></td>
                    <td className="text-right"><button onClick={() => openEdit(u)} className="admin-btn-edit mr-1">Edit</button><button onClick={() => handleDelete(u.id)} className="admin-btn-danger">Hapus</button></td>
                  </tr>
                ))}</tbody>
              </table>
            </div>
            <Pagination currentPage={page} totalPages={totalPages} onPageChange={setPage} />
          </>
        )}
      </div>
    </AdminLayout>
  );
}
