import React, { useState, useEffect } from 'react';
import { getDeletedUsers, restoreUser } from '../../services/users';
import './Trash.css';

function Trash({ onRefetch }) {
  const [deletedUsers, setDeletedUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [actionLoading, setActionLoading] = useState(null);

  useEffect(() => {
    loadDeletedUsers();
  }, []);

  const loadDeletedUsers = async () => {
    setLoading(true);
    setError(null);
    
    const result = await getDeletedUsers();
    
    if (result.success) {
      setDeletedUsers(result.data);
    } else {
      setError(result.message);
    }
    
    setLoading(false);
  };

  const handleRestore = async (id, name) => {
    if (!window.confirm(`"${name}" wirklich wiederherstellen?`)) {
      return;
    }

    setActionLoading(id);
    
    const result = await restoreUser(id);
    
    if (result.success) {
      // Remove from deleted list
      setDeletedUsers(deletedUsers.filter(u => u._id !== id));
      // Refresh main user list
      if (onRefetch) {
        onRefetch();
      }
    } else {
      alert(`Fehler: ${result.message}`);
    }
    
    setActionLoading(null);
  };

  const formatDate = (dateString) => {
    const date = new Date(dateString);
    return date.toLocaleString('de-DE', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  if (loading) {
    return <div className="trash-loading">Lade gelöschte Benutzer...</div>;
  }

  if (error) {
    return (
      <div className="trash-error">
        <h3>Fehler</h3>
        <p>{error}</p>
        <button onClick={loadDeletedUsers} className="btn-retry">
          Erneut versuchen
        </button>
      </div>
    );
  }

  return (
    <div className="trash-container">
      <div className="trash-header">
        <h2>🗑️ Papierkorb</h2>
        <p className="trash-description">
          {deletedUsers.length === 0
            ? 'Keine gelöschten Benutzer'
            : `${deletedUsers.length} gelöschte${deletedUsers.length === 1 ? 'r' : ''} Benutzer`}
        </p>
      </div>

      {deletedUsers.length === 0 ? (
        <div className="trash-empty">
          <div className="trash-empty-icon">🗑️</div>
          <p>Der Papierkorb ist leer</p>
        </div>
      ) : (
        <div className="trash-list">
          {deletedUsers.map((user) => (
            <div key={user._id} className="trash-item">
              <div className="trash-item-info">
                <h3>{user.name}</h3>
                <div className="trash-item-details">
                  <span className="trash-item-type">{user.type}</span>
                  <span className="trash-item-address">{user.address}</span>
                  <span className="trash-item-phone">{user.phone}</span>
                </div>
                <div className="trash-item-meta">
                  <span className="trash-item-deleted-date">
                    Gelöscht: {formatDate(user.deletedAt)}
                  </span>
                </div>
              </div>

              <div className="trash-item-actions">
                <button
                  onClick={() => handleRestore(user._id, user.name)}
                  disabled={actionLoading === user._id}
                  className="btn-restore"
                  title="Wiederherstellen"
                >
                  {actionLoading === user._id ? '⏳' : '↩️'}
                  <span>Wiederherstellen</span>
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

export default Trash;
