import React, { useState, useMemo } from 'react';
import UserCard from './UserCard';
import UserForm from './UserForm';
import SearchBar from './SearchBar';
import FilterPanel from './FilterPanel';
import Loading from '../common/Loading';
import ErrorMessage from '../common/ErrorMessage';
import './UserList.css';

const UserList = ({ users, loading, error, onAvailabilityToggle, onGPSUpdate, onUserCreate, onUserUpdate, onUserDelete, onPhotoUpload, onPhotoDelete }) => {
  const [editingUser, setEditingUser] = useState(null);
  const [showCreateForm, setShowCreateForm] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [filters, setFilters] = useState({
    availableOnly: false,
    type: null,
    sortBy: 'name'
  });

  const handleFilterChange = (key, value) => {
    setFilters(prev => ({ ...prev, [key]: value }));
  };

  const filteredAndSortedUsers = useMemo(() => {
    let filtered = [...users];

    // Search filter
    if (searchTerm) {
      const term = searchTerm.toLowerCase();
      filtered = filtered.filter(user =>
        user.name.toLowerCase().includes(term) ||
        user.address.toLowerCase().includes(term) ||
        user.phone.includes(term)
      );
    }

    // Available filter
    if (filters.availableOnly) {
      filtered = filtered.filter(user => user.available);
    }

    // Type filter
    if (filters.type) {
      filtered = filtered.filter(user => user.type === filters.type);
    }

    // Sort
    filtered.sort((a, b) => {
      switch (filters.sortBy) {
        case 'nameDesc':
          return b.name.localeCompare(a.name);
        case 'type':
          return a.type.localeCompare(b.type);
        case 'name':
        default:
          return a.name.localeCompare(b.name);
      }
    });

    return filtered;
  }, [users, searchTerm, filters]);

  if (loading) {
    return <Loading message="Lädt Nachsuchenführer..." />;
  }

  if (error) {
    return <ErrorMessage message={error} />;
  }

  const handleSave = async (userData) => {
    if (editingUser) {
      await onUserUpdate(editingUser._id, userData);
      setEditingUser(null);
    } else {
      await onUserCreate(userData);
      setShowCreateForm(false);
    }
  };

  const handleCancel = () => {
    setEditingUser(null);
    setShowCreateForm(false);
  };


  const handleEdit = (user) => {
    setEditingUser(user);
    setShowCreateForm(false);
    // Scroll to top to show the form
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleDelete = async (userId) => {
    await onUserDelete(userId);
  };

  return (
    <div className="user-list-admin">
      <div className="list-header-admin">
        <h2>Alle Nachsuchenführer</h2>
        <div className="header-actions">
          <div className="results-count">
            {filteredAndSortedUsers.length} von {users.length} Führern
          </div>
          {!showCreateForm && !editingUser && (
            <button
              className="create-button"
              onClick={() => {
                setShowCreateForm(true);
                setEditingUser(null);
              }}
            >
              + Neuer Nachsuchenführer
            </button>
          )}
        </div>
      </div>
      
      {(showCreateForm || editingUser) && (
        <div className="user-form-container">
          <UserForm
            user={editingUser}
            onSave={handleSave}
            onCancel={handleCancel}
          />
        </div>
      )}

      <SearchBar searchTerm={searchTerm} onSearchChange={setSearchTerm} />
      <FilterPanel filters={filters} onFilterChange={handleFilterChange} />
      {filteredAndSortedUsers.length === 0 ? (
        <div className="no-users">
          <p>Keine Nachsuchenführer gefunden.</p>
        </div>
      ) : (
        <div className="user-grid-admin">
          {filteredAndSortedUsers.map(user => (
            <UserCard
              key={user._id}
              user={user}
              onAvailabilityToggle={onAvailabilityToggle}
              onGPSUpdate={onGPSUpdate}
              onEdit={handleEdit}
              onDelete={handleDelete}
              onPhotoUpload={onPhotoUpload}
              onPhotoDelete={onPhotoDelete}
            />
          ))}
        </div>
      )}
    </div>
  );
};

export default UserList;
