'use client';

import React, { useState } from 'react';
import { createAdmin, updateAdminPassword } from '../actions';

interface UserFormProps {
  initialData?: any;
  onClose: () => void;
}

export default function UserForm({ initialData, onClose }: UserFormProps) {
  const [loading, setLoading] = useState(false);

  async function handleSubmit(formData: FormData) {
    setLoading(true);
    if (initialData) {
      await updateAdminPassword(initialData.id, formData);
    } else {
      await createAdmin(formData);
    }
    setLoading(false);
    onClose();
  }

  return (
    <div className="modal-overlay">
      <div className="modal-content">
        <div className="card-header">
          <h2 className="card-title">{initialData ? 'Şifre Değiştir' : 'Yeni Admin Ekle'}</h2>
          <button onClick={onClose} className="action-btn">✕</button>
        </div>
        <form action={handleSubmit} className="admin-form">
          {!initialData && (
            <div className="form-group">
              <label htmlFor="username">Kullanıcı Adı</label>
              <input
                id="username"
                name="username"
                className="admin-input"
                placeholder="Örn: ayrisdev"
                required
              />
            </div>
          )}
          {initialData && (
            <div className="form-group">
              <label>Kullanıcı Adı</label>
              <input
                className="admin-input"
                value={initialData.username}
                disabled
                style={{ opacity: 0.6 }}
              />
            </div>
          )}
          <div className="form-group">
            <label htmlFor="password">{initialData ? 'Yeni Şifre' : 'Şifre'}</label>
            <input
              id="password"
              name="password"
              type="password"
              className="admin-input"
              required
            />
          </div>
          <div style={{ display: 'flex', gap: '1rem', marginTop: '1rem' }}>
            <button type="submit" className="admin-btn" disabled={loading}>
              {loading ? 'Kaydediliyor...' : 'Kaydet'}
            </button>
            <button type="button" onClick={onClose} className="admin-btn" style={{ background: 'rgba(255,255,255,0.05)', color: '#fff' }}>
              İptal
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
