// components/AdminManager.js
'use client'
// components/AdminManager.js
import React, { useState, useEffect } from 'react';

function AdminManager() {
  const [admins, setAdmins] = useState([]);
  const [filteredAdmins, setFilteredAdmins] = useState([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [role, setRole] = useState('Staff');
  const [error, setError] = useState('');

  useEffect(() => {
    async function fetchAdmins() {
      try {
        const res = await fetch('/api/admins');
        const data = await res.json();
        setAdmins(data.admins);
        setFilteredAdmins(data.admins);
      } catch (err) {
        setError('Failed to fetch data');
      }
    }
    fetchAdmins();
  }, []);

  useEffect(() => {
    const filtered = admins.filter(admin => admin.name.toLowerCase().includes(searchTerm.toLowerCase()) || admin.email.toLowerCase().includes(searchTerm.toLowerCase()));
    setFilteredAdmins(filtered);
  }, [searchTerm, admins]);

  const handleSubmit = async (event) => {
    event.preventDefault();
    const newAdmin = { name, email, role };
    try {
      const res = await fetch('/api/admins', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(newAdmin),
      });
      const addedAdmin = await res.json();
      setAdmins([...admins, addedAdmin]);
      setName('');
      setEmail('');
      setRole('Staff');
      setError('');
    } catch (err) {
      setError('Error adding admin');
    }
  };

  return (
    <div className="p-8 bg-white shadow-md rounded-lg text-black">
      <h1 className="text-2xl font-bold mb-6">Admin Management</h1>
      <input
        type="text"
        placeholder="Search admins..."
        className="border p-2 rounded w-full mb-6"
        onChange={(e) => setSearchTerm(e.target.value)}
      />
      {error && <div className="bg-red-100 text-red-700 p-3 rounded mb-5">{error}</div>}
      <form onSubmit={handleSubmit} className="grid grid-cols-3 gap-4 mb-4">
        <input type="text" value={name} onChange={(e) => setName(e.target.value)} placeholder="Name" className="border p-2 rounded" />
        <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="Email" className="border p-2 rounded" />
        <select value={role} onChange={(e) => setRole(e.target.value)} className="border p-2 rounded">
          <option value="Staff">Staff</option>
          <option value="Administrator">Administrator</option>
          <option value="Supervisor">Supervisor</option>
        </select>
        <button type="submit" className="col-span-3 bg-blue-500 text-white px-6 py-2 rounded hover:bg-blue-600">Add Admin</button>
      </form>
      <div className="overflow-x-auto">
        <table className="w-full">
          <thead className="bg-gray-100">
            <tr>
              <th className="text-left p-4">Name</th>
              <th className="text-left p-4">Email</th>
              <th className="text-left p-4">Role</th>
              <th className="text-left p-4">Actions</th>
            </tr>
          </thead>
          <tbody>
            {filteredAdmins.map((admin, index) => (
              <tr key={index} className="border-t">
                <td className="p-4">{admin.name}</td>
                <td className="p-4">{admin.email}</td>
                <td className="p-4">{admin.role}</td>
                <td className="p-4">
                  <button className="bg-red-500 text-white px-4 py-1 rounded hover:bg-red-600 mr-2">Disable</button>
                  <button className="bg-green-500 text-white px-4 py-1 rounded hover:bg-green-600">Edit</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

export default AdminManager;

