'use client';

import React, { useState } from 'react';
import UserForm from '../components/UserForm';
import DeleteButton from '../components/DeleteButton';
import { deleteAdmin } from '../actions';

interface UserManagerProps {
  users: any[];
}

export default function UserManager({ users }: UserManagerProps) {
  const [showForm, setShowForm] = useState(false);
  const [editingUser, setEditingUser] = useState<any>(null);

  const handleEdit = (user: any) => {
    setEditingUser(user);
    setShowForm(true);
  };

  const handleClose = () => {
    setShowForm(false);
    setEditingUser(null);
  };

  return (
    <div className="admin-users">
      <div className="admin-page-header" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '2rem' }}>
        <div>
          <h1>Kullanıcılar</h1>
          <p>Yönetici hesaplarını yönetin</p>
        </div>
        <button className="admin-btn" onClick={() => setShowForm(true)}>
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{width: '16px'}}><line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" /></svg>
          Yeni Admin Ekle
        </button>
      </div>

      <div className="admin-card">
        <table className="admin-table">
          <thead>
            <tr>
              <th>Kullanıcı Adı</th>
              <th>Oluşturulma</th>
              <th>İşlemler</th>
            </tr>
          </thead>
          <tbody>
            {users.map((user) => (
              <tr key={user.id}>
                <td style={{ fontWeight: 500, color: '#fff' }}>{user.username}</td>
                <td style={{ color: 'var(--text-muted)', fontSize: '0.85rem' }}>
                  {new Date(user.createdAt).toLocaleDateString('tr-TR')}
                </td>
                <td className="actions-cell">
                  <button className="action-btn" onClick={() => handleEdit(user)}>Şifre Değiştir</button>
                  {users.length > 1 && (
                    <DeleteButton onDelete={async () => { await deleteAdmin(user.id); }} />
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {showForm && (
        <UserForm 
          initialData={editingUser} 
          onClose={handleClose} 
        />
      )}
    </div>
  );
}
