import { useState, useCallback, useEffect } from 'react';
import { usersApi, rolesApi } from '../api';
import type { User, Role, UserFilters, CreateUserDto, UpdateUserDto } from '../types';

interface UseUsersState {
  users: User[];
  total: number;
  page: number;
  totalPages: number;
  isLoading: boolean;
  error: string | null;
}

interface UseUsersReturn extends UseUsersState {
  filters: UserFilters;
  setFilters: (filters: UserFilters) => void;
  refresh: () => Promise<void>;
  createUser: (data: CreateUserDto) => Promise<User>;
  updateUser: (id: string, data: UpdateUserDto) => Promise<User>;
  deleteUser: (id: string) => Promise<void>;
  activateUser: (id: string) => Promise<void>;
  deactivateUser: (id: string) => Promise<void>;
}

export function useUsers(initialFilters?: UserFilters): UseUsersReturn {
  const [state, setState] = useState<UseUsersState>({
    users: [],
    total: 0,
    page: 1,
    totalPages: 1,
    isLoading: true,
    error: null,
  });

  const [filters, setFilters] = useState<UserFilters>(initialFilters || { page: 1, limit: 10 });

  const fetchUsers = useCallback(async () => {
    setState((prev) => ({ ...prev, isLoading: true, error: null }));
    try {
      const response = await usersApi.getAll(filters);
      setState({
        users: response.data,
        total: response.meta.total,
        page: response.meta.page,
        totalPages: response.meta.totalPages,
        isLoading: false,
        error: null,
      });
    } catch (err) {
      setState((prev) => ({
        ...prev,
        isLoading: false,
        error: err instanceof Error ? err.message : 'Error al cargar usuarios',
      }));
    }
  }, [filters]);

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

  const createUser = async (data: CreateUserDto): Promise<User> => {
    const user = await usersApi.create(data);
    await fetchUsers();
    return user;
  };

  const updateUser = async (id: string, data: UpdateUserDto): Promise<User> => {
    const user = await usersApi.update(id, data);
    await fetchUsers();
    return user;
  };

  const deleteUser = async (id: string): Promise<void> => {
    await usersApi.delete(id);
    await fetchUsers();
  };

  const activateUser = async (id: string): Promise<void> => {
    await usersApi.activate(id);
    await fetchUsers();
  };

  const deactivateUser = async (id: string): Promise<void> => {
    await usersApi.deactivate(id);
    await fetchUsers();
  };

  return {
    ...state,
    filters,
    setFilters,
    refresh: fetchUsers,
    createUser,
    updateUser,
    deleteUser,
    activateUser,
    deactivateUser,
  };
}

// Hook for single user
export function useUser(id: string | undefined) {
  const [user, setUser] = useState<User | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchUser = useCallback(async () => {
    if (!id) {
      setIsLoading(false);
      return;
    }

    setIsLoading(true);
    setError(null);
    try {
      const data = await usersApi.getById(id);
      setUser(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error al cargar usuario');
    } finally {
      setIsLoading(false);
    }
  }, [id]);

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

  return { user, isLoading, error, refresh: fetchUser };
}

// Hook for roles
export function useRoles() {
  const [roles, setRoles] = useState<Role[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchRoles = async () => {
      try {
        const data = await rolesApi.getAll();
        setRoles(data);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Error al cargar roles');
      } finally {
        setIsLoading(false);
      }
    };

    fetchRoles();
  }, []);

  return { roles, isLoading, error };
}
