import { useState, useEffect } from 'react';
import { User, UserFormData } from '../types/auth';
import { userService } from '../services/userService';


export function useUserManagement() {
  const [users, setUsers] = useState<User[]>([]);
  const [selectedUser, setSelectedUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

  const fetchUsers = async () => {
    try {
      setLoading(true);
      const fetchedUsers = await userService.getUsers();
      setUsers(fetchedUsers);
      setError(null);
    } catch (err) {
      setError('Ошибка получения списка пользователей');
      console.error('Ошибка получения списка пользователей:', err);
    } finally {
      setLoading(false);
    }
  };

  const handlePermissionChange = async (
    categoryId: number,
    action: 'create' | 'edit' | 'delete',
    value: boolean
  ) => {
    if (!selectedUser) return;

    try {
      const updatedPermissions = {
        ...selectedUser.permissions,
        categories: {
          ...selectedUser.permissions.categories,
          [categoryId]: {
            ...selectedUser.permissions.categories[categoryId],
            [action]: value,
          },
        },
      };

      const updatedUser = await userService.updateUserPermissions(
        selectedUser.id,
        updatedPermissions
      );

      setSelectedUser(updatedUser);
      setUsers(users.map((user) => 
        user.id === selectedUser.id ? updatedUser : user
      ));
      setError(null);
    } catch (err) {
      setError('Failed to update permissions');
      console.error('Error updating permissions:', err);
    }
  };

  const handleCityChange = async (city: number, checked: boolean) => {
    if (!selectedUser) return;

    try {
      const updatedCities = checked
        ? [...selectedUser.permissions.cities, city]
        : selectedUser.permissions.cities.filter((c) => c !== city);

      const updatedPermissions = {
        ...selectedUser.permissions,
        cities: updatedCities,
      };

      const updatedUser = await userService.updateUserPermissions(
        selectedUser.id,
        updatedPermissions
      );

      setSelectedUser(updatedUser);
      setUsers(users.map((user) => 
        user.id === selectedUser.id ? updatedUser : user
      ));
      setError(null);
    } catch (err) {
      setError('Failed to update city permissions');
      console.error('Error updating city permissions:', err);
    }
  };

  const createUser = async (formData: UserFormData) => {
    try {
      const newUser = await userService.createUser(formData);
      setUsers([...users, newUser]);
      setError(null);
    } catch (err) {
      setError('Failed to create user');
      throw err;
    }
  };

  const updateUser = async (userId: string, formData: UserFormData) => {
    try {
      const updatedUser = await userService.updateUser(userId, formData);
      setUsers(users.map(user => user.id === userId ? updatedUser : user));
      setError(null);
    } catch (err) {
      setError('Failed to update user');
      throw err;
    }
  };

  const deleteUser = async (userId: string) => {
    try {
      await userService.deleteUser(userId);
      setUsers(users.filter(user => user.id !== userId));
      if (selectedUser?.id === userId) {
        setSelectedUser(null);
      }
      setError(null);
    } catch (err) {
      setError('Failed to delete user');
      throw err;
    }
  };

  return {
    users,
    selectedUser,
    loading,
    error,
    setSelectedUser,
    handlePermissionChange,
    handleCityChange,
    createUser,
    updateUser,
    deleteUser
  };
}